using CheckBoxHeaderDemo;
using demo.ServiceRef;
using demo.Tool;
using Microsoft.VisualBasic;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using ZXing;
namespace demo
{
    public partial class Form1 : Form
    {
        private static ServerSQL.operateSoapClient sqlServer;
        OpaqueCommand cmd = new OpaqueCommand();
        UesrModel userData;
        string IsSelect = "";
        string EndDate = "";
        private string reportUrl = string.Empty;
        
        // 系统托盘图标
        private NotifyIcon notifyIcon;
        
        // 当前显示的患者数据通知弹窗
        private MessageNotificationForm currentNotificationForm;
        private ContextMenuStrip trayContextMenu;
        
        // 数据刷新定时器
        private System.Windows.Forms.Timer timerDataRefresh;
        //此构造方法无效
        public Form1()
        {
            InitializeComponent();
            //测试同步效果

            sqlServer = new ServerSQL.operateSoapClient();
            dataGridView1.AllowUserToAddRows = false;
            invokeShow = updateForm;
            //invokepayStateQuery = payStateQuery;
            invokeShowPreCrePay = updatePreCrePay;
            invokeQRBarCodePay = updataQRBarCodePay;
            invokeQRBarCodePay2 = updataQRBarCodePay2;
            invokeSetFoucs = SetFoucs;
            invokeSetFoucsKH = SetFoucsKH;
            invokepayStateQuery = updateFromPayStateQuery;
            queryDate = getNowDateTime().ToString("yyyy-MM-dd");
            EndDate = getNowDateTime().ToString("yyyy-MM-dd");
            dataGridView1.Visible = false;
            dataGridView2.Visible = false;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 只选择整行，不改变颜色或字体样式
            IsSelect = ConfigurationManager.AppSettings["IsSelect"].ToString();
            setCmd();
            
            // 初始化系统托盘图标
            InitializeSystemTray();
        }

        public Form1(UesrModel userInfo)
        {
            InitializeComponent();
            
            userData = userInfo;

            this.Text = "门诊充值计费程序 - 版本 V" + Assembly.GetEntryAssembly().GetName().Version.ToString();
            // 设置文本框的ImeMode属性为Disable，禁用输入法，实现半角英文输入
            textBoxcx.ImeMode = ImeMode.Disable;
            this.Text = "门诊充值计费程序 [] 当前用户：" + userData.user_id + " " + userData.user_name;
            lal_user_id.Text = userData.user_id;
            lal_user_name.Text = userData.user_name;
            sqlServer = new ServerSQL.operateSoapClient();
            dataGridView1.AllowUserToAddRows = false;
            invokeShow = updateForm;
            //invokepayStateQuery = payStateQuery;
            invokeShowPreCrePay = updatePreCrePay;
            invokeQRBarCodePay = updataQRBarCodePay;
            invokepayStateQuery = updateFromPayStateQuery;
            invokeSetFoucs = SetFoucs;
            invokeSetFoucsKH = SetFoucsKH;
            queryDate = getNowDateTime().ToString("yyyy-MM-dd");
            EndDate = getNowDateTime().ToString("yyyy-MM-dd");
            dataGridView1.Visible = false;
            dataGridView2.Visible = false;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 只选择整行，不改变颜色或字体样式
            IsSelect = ConfigurationManager.AppSettings["IsSelect"].ToString();
            setCmd();
            
            // 初始化系统托盘图标
            InitializeSystemTray();
        }
        void setCmd()
        {
            List<Item> item = new List<Item>();
            for (int i = 1; i < 8; i++)
            {
                item.Add(new Item() { ID = i, Name = "查询" + i.ToString() + "天" });
            }
            item.Add(new Item() { ID = 30, Name = "查询一个月" });
            item.Add(new Item() { ID = 60, Name = "查询两个月" });
            item.Add(new Item() { ID = 90, Name = "查询三个月" });
            item.Add(new Item() { ID = 365, Name = "查询一年" });
            comboBox1.DataSource = item;
            comboBox1.DisplayMember = "Name"; // 显示Name属性
            comboBox1.ValueMember = "ID"; // 存储ID属性作为值
            comboBox1.SelectedIndex = 0;
            comboBox1.SelectionChangeCommitted += new EventHandler(comboBox1_SelectedIndexChanged);


            List<Item> itemType = new List<Item>();
            itemType.Add(new Item() { ID = 0, Name = "全部" });
            itemType.Add(new Item() { ID = 1, Name = "处方单" });
            itemType.Add(new Item() { ID = 2, Name = "检查单" });
            itemType.Add(new Item() { ID = 3, Name = "检验单" });
            itemType.Add(new Item() { ID = 3, Name = "治疗单" });
            comboBox2.DataSource = itemType;
            comboBox2.DisplayMember = "Name"; // 显示Name属性
            comboBox2.ValueMember = "ID"; // 存储ID属性作为值
            comboBox2.SelectedIndex = 0;
            comboBox2.SelectionChangeCommitted += new EventHandler(comboBox2_SelectedIndexChanged);

            //绑定检查检验互认事件
            bt_lis.Click += new EventHandler(openLisExamWebView);
            bt_exam.Click += new EventHandler(openLisExamWebView);

            // 加载本地数据
            LoadLocalData();
        }
        
        #region
        private void ExcuteEXE()
        {
            try
            {
                //实例一个process类
                Process process = new Process();
                //判断进程是否存在，存在就关闭进程
                Process[] proc = Process.GetProcessesByName("门诊充值计费程序");
                if (proc.Length > 0)
                {
                    foreach (Process p in proc)
                    {
                        p.Kill();
                    }
                }

            }
            catch (Exception)
            {

            }


        }
        
        /// <summary>
        /// 刷新本地数据窗口，确保显示最新数据且无重复
        /// </summary>
        private void RefreshLocalDataGrid()
        {
            try
            {
                // 重新加载本地数据
                LoadLocalData();
            }
            catch
            {
                AddMessageToList($"[数据刷新] 刷新本地数据窗口失败");
            }
        }
        #endregion

        #region --------------------------------扫码付相关-------------------------------
        private Thread threadQRPayPreCreat;
        public delegate void FormShowPreCrePay();
        public FormShowPreCrePay invokeShowPreCrePay;
        /// <summary>
        /// 扫码付
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.textBoxPayAmount.Text))
                {
                    MessageBox.Show("请输入充值金额！");
                    return;
                }
                if (Convert.ToDecimal(this.textBoxPayAmount.Text) <= 0)
                {
                    MessageBox.Show("计算得到金额小于等于0，不允许充值！");
                    return;
                }
                if (string.IsNullOrEmpty(this.labelhzid.Text))
                {
                    MessageBox.Show("请先查询患者信息，再进行充值！");
                    return;
                }
                textBoxFKM.Text = "";
                this.OutTradeNo.Text = "";
                cmd.ShowOpaqueLayer(this, 100, true);
                threadQRPayPreCreat = new Thread(QRPayPreCreatRequest);
                threadQRPayPreCreat.Start(); // 直接传递参数给DoWork方法
            }
            catch
            {
                MessageBox.Show("失败！异常");
            }

        }
        private QRPayPreCreatOutput outputPreCreate;
        private string erroMsg;
        void QRPayPreCreatRequest()
        {


            outputPreCreate = new QRPayPreCreatOutput();
            ServiceRef.HospitalService_XXXXClient clientService = new ServiceRef.HospitalService_XXXXClient();
            string OutTradeNo = "";
            ServiceRef.ResultBase reslut = new ServiceRef.ResultBase();
            reslut = clientService.GenerateSN();
            if (reslut != null)
            {
                OutTradeNo = reslut.ReturnValue.ToString();
                QRPayPreCreatInput requreInput = new QRPayPreCreatInput()
                {
                    OutTradeNo = OutTradeNo,
                    TotalAmount = this.textBoxPayAmount.Text,
                    Subject = "门诊充值",
                    Body = "门诊充值",
                    Terminal = "001",
                    PatientName = patinfo.PatientName,
                    IDCardNo = patinfo.PatientIDCardNO,
                    PatientID = patinfo.PatientID,
                    Operation = "门诊充值",

                    SellerName = "",
                };

                requreInput.PayType = EnumQRPay.weixin;
                sqlServer.AddOrderMsg(patinfo.PatientID, patinfo.PatientName, patinfo.PatientIDCardNO, OutTradeNo, requreInput.TotalAmount, patinfo.CardNO, userData.user_id);
                operateLog.WriteLog("执行生成二维码开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("患者ID：" + requreInput.PatientID);
                operateLog.WriteLog("患者姓名：" + requreInput.PatientName);
                operateLog.WriteLog("订单金额：" + requreInput.TotalAmount);
                outputPreCreate = clientService.QRPayPreCreatRequest(requreInput);
            }
            else
            {
                outputPreCreate = null;
                erroMsg = "获取流水号失败！";
            }
            if (this.Created)
            {
                this.BeginInvoke(this.invokeShowPreCrePay);
            }

        }
        void updatePreCrePay()
        {
            cmd.HideOpaqueLayer();
            if (outputPreCreate == null)
            {
                MessageBox.Show(erroMsg);
            }
            else if (outputPreCreate.Result != null && outputPreCreate.Result == "0")
            {
                this.pictureBox1.Visible = true;
                lblwaittip.Visible = true;
                Bitmap bit = QrCodeHelper.CreateQRCode(outputPreCreate.CodeUrl);
                this.pictureBox1.Image = bit;
                this.OutTradeNo.Text = outputPreCreate.OutTradeNo;
            }
            else
            {
                MessageBox.Show("生成二维码失败：" + outputPreCreate.Message);
            }
        }
        #endregion


        #region ------------------------查询患者/处方相关----------------------------
        bool IsCSH = false;
        private Thread threadQueryPatient;
        private static ServiceRef.QueryPatientInfoOut patinfo;
        public delegate void FormShowInvoke();
        public FormShowInvoke invokeShow;
        string queryDate = "";
        /// <summary>
        /// 查患者信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //payDetailList = new List<Tool.PayDetail>();

            if (Regex.IsMatch(textBoxcx.Text, @"[\uFF00-\uFFEF]"))
            {
                MessageBox.Show("输入包含全角符号，请重新输入！", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 清空输入框
                textBoxcx.Text = "";
                return;
            }

            string qrCode = this.textBoxcx.Text;
            operateLog.WriteLog("执行查询患者信息开始qrCode：" + qrCode);

            if (qrCode.IndexOf("|") > 0 || qrCode.IndexOf("=") > 0 || qrCode.IndexOf("772:") == 0)  //;81293687|82665666?
            {
                textBoxcx.Focus();
                cmd.ShowOpaqueLayer(this, 100, true);
                lblwaittip.Visible = false;
                this.pictureBox1.Visible = false;
                this.OutTradeNo.Text = "";
                this.textBoxPayAmount.Text = "0";
                string str = this.textBoxcx.Text;
                this.textBoxPayAmount.ReadOnly = true;
                int selectedValue = Convert.ToInt32(comboBox1.SelectedValue);
                EndDate = getNowDateTime().AddDays(-selectedValue).ToString("yyyy-MM-dd");
                //dateTimePicker1.Value = DateTime.Now; // 设置当前时间
                threadQueryPatient = new Thread(new ParameterizedThreadStart(DoWork));
                threadQueryPatient.Start(str); // 直接传递参数给DoWork方法
            }
            else
            {
                MessageBox.Show("该类型卡号暂不支持充值！");
                this.textBoxcx.Text = "";
                textBoxcx.Focus();

            }



        }
        private void DoWork(object obj)
        {
            try
            {
                string str = obj as string;
                operateLog.WriteLog("执行查询患者信息开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("输入卡号：" + str);
                patinfo = new QueryPatientInfoOut();
                //return;
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                ServiceRef.QueryPatientInfoIn input = new ServiceRef.QueryPatientInfoIn();
                input.QueryType = "1";
                input.CardNO = str; //"772:905dd6b8-8c6d-4383-aab7-deb2ac08dff7:1";//
                input.CardName = "";
                input.CardTypeID = "1";
                if (str.Length > 15)
                    input.CardTypeID = "3";
                if (str.Length > 18)
                    input.CardTypeID = "4";
                input.TerminalCode = "001";
                patinfo = clientService.QueryPatientInfoCommon(input);
                operateLog.WriteLog("执行查询患者信息结束");
                operateLog.WriteLog("执行查询患者信息出参：" + patinfo.CardNO + patinfo.PatientName);
            }
            catch
            {

            }
            if (this.Created)
            {
                this.BeginInvoke(this.invokeShow);
            }
        }
        private void updateForm()
        {
            try
            {
                operateLog.WriteLog("渲染患者信息开始");
                cmd.HideOpaqueLayer();
                this.textBoxcx.Text = "";
                textBoxcx.Focus();

                if (patinfo != null && patinfo.Result == "0" && (!string.IsNullOrEmpty(patinfo.PatientName)))
                {
                    if (!string.IsNullOrEmpty(patinfo.CardNO))
                        this.labelkh.Text = patinfo.CardNO;
                    else
                        this.labelkh.Text = patinfo.CardNO;
                    this.labelhzid.Text = patinfo.PatientID;
                    this.labelName.Text = patinfo.PatientName;
                    this.label1Age.Text = patinfo.PatientAge;

                    if (!string.IsNullOrEmpty(patinfo.PatientIDCardNO))
                    {
                        this.PatientIDCardNO.Text = MaskId(patinfo.PatientIDCardNO);
                    }
                    else
                    {
                        this.PatientIDCardNO.Text = patinfo.PatientIDCardNO;
                    }



                    this.PatientTelephone.Text = patinfo.PatientTelephone;
                    this.Balance.Text = patinfo.Balance;
                    this.Address.Text = patinfo.Address;
                    this.PatientTelephone.Text = patinfo.PatientTelephone;
                    this.label1Sex.Text = patinfo.PatientSex;
                    this.PatientBirthday.Text = patinfo.PatientBirthday;
                    this.OutTradeNo.Text = "";
                    operateLog.WriteLog("渲染患者信息结束");
                    QueryToPayRecipeInfoList(patinfo);
                    this.textBoxPayAmount.Text = "0";
                    this.textBoxPayAmount.ReadOnly = true;

                }
                else
                {
                    patinfo = new QueryPatientInfoOut();
                    this.labelkh.Text = "-";
                    this.labelhzid.Text = "-";
                    this.labelName.Text = "-";
                    this.label1Age.Text = "-";
                    this.PatientIDCardNO.Text = "-";
                    this.PatientTelephone.Text = "-";
                    this.Balance.Text = "-";
                    this.Address.Text = "-";
                    this.PatientTelephone.Text = "-";
                    this.label1Sex.Text = "-";
                    this.PatientBirthday.Text = "-";
                    MessageBox.Show("查询患者信息失败！" + patinfo.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询患者信息异常：" + ex.Message);
            }

        }




        public static string MaskId(string id)
        {
            if (id.Length <= 4) return id; // 如果身份证号码太短，则不处理
            StringBuilder sb = new StringBuilder(id);
            for (int i = 4; i < id.Length - 4; i++)
            {
                sb[i] = '*';
            }
            return sb.ToString();
        }


        private static Dictionary<string, ServiceRef.QueryToPayRecipeDetailInfoOut[]> PayDetail;
        /// <summary>
        /// 查询待缴费处方
        /// </summary>
        /// <param name="patinfo"></param>
        public void QueryToPayRecipeInfoList(ServiceRef.QueryPatientInfoOut patinfo)
        {
            try
            {
                operateLog.WriteLog("执行查询处方开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("患者ID：" + patinfo.PatientID);
                operateLog.WriteLog("患者ID：" + patinfo.PatientName);
                operateLog.WriteLog("查询开始时间：" + EndDate);
                operateLog.WriteLog("查询结束时间" + queryDate);
                PayDetail = new Dictionary<string, QueryToPayRecipeDetailInfoOut[]>();
                //dataGridView1 = new DataGridView();
                string typeName = (comboBox2.SelectedItem as Item).Name;
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                ServiceRef.QueryToPayRecipeInfoIn inGetRecipe = new ServiceRef.QueryToPayRecipeInfoIn();
                inGetRecipe.PatientID = patinfo.PatientID;
                inGetRecipe.RegFlow = "";
                inGetRecipe.TerminalCode = "001";
                inGetRecipe.medicareType = "0";
                inGetRecipe.uerInfo = "";
                inGetRecipe.yqId = "LZ001";
                inGetRecipe.StartDate = EndDate;
                inGetRecipe.EndDate = queryDate;
                dataGridView2.Visible = false;
                ServiceRef.BaseListOfQueryToPayRecipeInfoOuto4BIDE2W billitemArray = clientService.QueryToPayRecipeInfoList(inGetRecipe);
                if (billitemArray != null && billitemArray.Result == "0")
                {
                    operateLog.WriteLog("执行查询处方数量出参：" + billitemArray.list.Count());
                    if (billitemArray.list.Count() > 0)
                    {
                        operateLog.WriteLog("声明DataTable");
                        DataTable dt = new DataTable();
                        try
                        {
                            dt.Columns.Add("处方号", typeof(string));
                            dt.Columns.Add("就诊次数", typeof(string));
                            dt.Columns.Add("处方类型", typeof(string));
                            dt.Columns.Add("开单科室", typeof(string));
                            dt.Columns.Add("开单医生", typeof(string));
                            dt.Columns.Add("处方金额", typeof(string));
                            dt.Columns.Add("就诊id", typeof(string));
                        }
                        catch
                        {
                            operateLog.WriteLog("DataTable初始化异常");
                        }
                        operateLog.WriteLog("遍历处方列表开始");
                        decimal money = 0;
                        for (int i = 0; i < billitemArray.list.Count(); i++)
                        {
                            operateLog.WriteLog("遍历处方列表第：" + i);
                            var item = billitemArray.list[i];
                            operateLog.WriteLog("处方号：" + item.RecipeNO);
                            operateLog.WriteLog("TerminalCode：" + inGetRecipe.TerminalCode);
                            operateLog.WriteLog("PatientID：" + patinfo.PatientID);
                            operateLog.WriteLog("RecipeTime：" + item.RecipeTime.ToString());
                            operateLog.WriteLog("yqId：" + inGetRecipe.yqId);
                            operateLog.WriteLog("MoOrderId：" + item.MoOrder);
                            operateLog.WriteLog("ItemType：" + item.ItemType);

                            money = money + decimal.Parse(item.Amount);
                            ServiceRef.QueryToPayRecipeDetailInfoIn inGetRecipeDetail = new ServiceRef.QueryToPayRecipeDetailInfoIn();
                            inGetRecipeDetail.RecipeNO = item.RecipeNO;//处方号
                            inGetRecipeDetail.TerminalCode = inGetRecipe.TerminalCode;
                            inGetRecipeDetail.PatientID = patinfo.PatientID;
                            inGetRecipeDetail.RecipeTime = item.RecipeTime.ToString();
                            inGetRecipeDetail.RegFlow = "";
                            inGetRecipeDetail.yqId = inGetRecipe.yqId;
                            inGetRecipeDetail.MoOrderId = item.MoOrder;
                            inGetRecipeDetail.ItemType = item.ItemType;

                            operateLog.WriteLog("执行查询处方明细数量入参：" + Newtonsoft.Json.JsonConvert.SerializeObject(inGetRecipeDetail));
                            ServiceRef.BaseListOfQueryToPayRecipeDetailInfoOuto4BIDE2W detailArray = clientService.QueryToPayRecipeDetailInfoList(inGetRecipeDetail);
                            if (detailArray.Result == "0" && detailArray.list.Length > 0)
                            {
                                operateLog.WriteLog("执行查询处方明细数量出参：" + detailArray.list.Length);
                                item.Amount = detailArray.list.Sum(x => Convert.ToDecimal(x.Costs)).ToString();
                                PayDetail.Add(item.RecipeNO, detailArray.list);
                                if (typeName == "全部")
                                    dt.Rows.Add(item.RecipeNO, item.SeeNo, item.ItemName, item.DepartmentName, item.DoctorName, item.Amount, item.Diagnosis);
                                else if (item.ItemName == typeName)
                                    dt.Rows.Add(item.RecipeNO, item.SeeNo, item.ItemName, item.DepartmentName, item.DoctorName, item.Amount, item.Diagnosis);
                            }
                            else
                            {
                                operateLog.WriteLog("执行查询处方明细失败出参：" + detailArray.Message);
                            }


                        }
                        this.textBoxPayAmount.Text = "0";// money.ToString("F2");

                        // 绑定到DataGridView
                        dataGridView1.DataSource = dt;
                        InsertCheckBoxColumn(this.dataGridView1, 0);
                        //dataGridView1.CellContentClick += DgInfo_CellContentClick;
                        dataGridView1.Visible = true;
                        operateLog.WriteLog("绑定到DataGridView");
                    }
                    else
                    {
                        dataGridView1.Visible = false;
                        dataGridView1.DataSource = null;
                        MessageBox.Show("待缴费查询失败！");
                        textBoxcx.Focus();
                        return;
                    }
                    //cmd.HideOpaqueLayer();
                }
                else
                {
                    dataGridView1.Visible = false;
                    dataGridView1.DataSource = null;
                    //cmd.HideOpaqueLayer();
                    //MessageBox.Show("待缴费查询失败！" + billitemArray.Message);
                    textBoxcx.Focus();
                    return;
                }
            }
            catch
            {
                operateLog.WriteLog("执行查询处方异常");
            }
        }


        public void InsertCheckBoxColumn(DataGridView dgv, int index)
        {

            try
            {
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                DataTable dtPlanProducts = dgv.DataSource as DataTable; //获取数据源
                if (dtPlanProducts == null)
                    throw new NoNullAllowedException(dgv.Name + "控件未绑定数据源");

                int originalColumnsCount = dtPlanProducts.Columns.Count;    //获取原始数据源列的个数
                if (index < 0 || index > originalColumnsCount)
                    throw new IndexOutOfRangeException();

                if (IsCSH == false)
                {
                    dgv.CellClick += new DataGridViewCellEventHandler(dgv_CellClick);   //注册单元格单击事件
                    IsCSH = true;
                }


                //添加CheckBox列
                dtPlanProducts.Columns.Add(null, typeof(bool));
                dgv.Columns[originalColumnsCount].DisplayIndex = index;

                //添加CheckBox表头
                DatagridViewCheckBoxHeaderCell cbHeaderProducts = new DatagridViewCheckBoxHeaderCell();
                dgv.Columns[originalColumnsCount].HeaderCell = cbHeaderProducts;
                dgv.Columns[originalColumnsCount].Resizable = DataGridViewTriState.False;
                dgv.Columns[originalColumnsCount].Width = 80;
                dgv.Columns[originalColumnsCount].HeaderText = "选择";
                dgv.Columns[originalColumnsCount].Name = "选择";
            }
            catch
            {
                operateLog.WriteLog("绑定InsertCheckBoxColumn异常");
            }
        }

        public void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0) return;
            DataGridView dgv = sender as DataGridView;

            if (dgv.Columns[e.ColumnIndex].HeaderCell.GetType() == typeof(DatagridViewCheckBoxHeaderCell))
            {
                #region 点击选择
                if (e.RowIndex < 0) //单击表头
                {
                    DatagridViewCheckBoxHeaderCell cell = dgv.Columns[e.ColumnIndex].HeaderCell as DatagridViewCheckBoxHeaderCell;
                    cell.Checked = !cell.Checked;
                    foreach (DataGridViewRow row in dgv.Rows)
                    {
                        if (row.IsNewRow) continue; //不处理新列
                        if (row.Cells[e.ColumnIndex] == dgv.CurrentCell)
                            dgv.EndEdit();

                        row.Cells[e.ColumnIndex].Value = cell.Checked;  //表头状态赋予到记录
                    }
                }
                else if (dgv.Rows[e.RowIndex].IsNewRow) { } //不处理新列的单击事件
                else   //单击记录
                {
                    DataGridViewCell currentCell = dgv[e.ColumnIndex, e.RowIndex];
                    object currentValue = currentCell.Value;

                    //未初始化的记录，按false处理
                    if (currentValue == null || currentCell.Value is System.DBNull || Convert.ToBoolean(currentValue) == false)
                    {
                        currentCell.Value = true;   //选中

                        //判断是否全部选中
                        bool enumState = true;
                        foreach (DataGridViewRow row in dgv.Rows)
                        {
                            if (row.IsNewRow) continue;
                            if (row.Cells[e.ColumnIndex].Value is System.DBNull || Convert.ToBoolean(row.Cells[e.ColumnIndex].Value.ToString()) == false)
                            {
                                enumState = false;
                                break;
                            }
                        }

                        //如果全选，选中表头
                        if (enumState == true)
                            (dgv.Columns[e.ColumnIndex].HeaderCell as DatagridViewCheckBoxHeaderCell).Checked = true;
                    }
                    else
                    {
                        currentCell.Value = false;  //取消选中

                        //取消选中表头
                        DatagridViewCheckBoxHeaderCell cell = dgv.Columns[e.ColumnIndex].HeaderCell as DatagridViewCheckBoxHeaderCell;
                        if (cell.Checked)
                            cell.Checked = false;
                    }

                    //刷新显示当前单元格
                    dgv.EndEdit();
                }
                #endregion
                List<string> List = new List<string>();
                var count = dgv.Rows;
                decimal ToMoney = 0;
                for (global::System.Int32 i = 0; i < count.Count; i++)
                {
                    var boolStr = dgv.Rows[i].Cells["选择"].Value.ToString();
                    if (boolStr == "True")
                    {
                        //item.Cells["处方号"].Value.ToString();
                        ToMoney += Convert.ToDecimal(dgv.Rows[i].Cells["处方金额"].Value.ToString());
                        dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
                        List.Add(dgv.Rows[i].Cells["处方号"].Value.ToString());
                    }
                    else
                    {
                        dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
                    }
                }
                if (ToMoney == 0)
                {
                    textBoxPayAmount.Text = "0";
                }
                else
                {
                    textBoxPayAmount.Text = (ToMoney - Convert.ToDecimal(Balance.Text)).ToString();
                }

                dataGridView2.Visible = true;
                DataTable dt = new DataTable();
                //dt.Columns.Add("id", typeof(string));
                dt.Columns.Add("项目", typeof(string));
                dt.Columns.Add("单价（元）", typeof(string));
                dt.Columns.Add("数量", typeof(string));
                dt.Columns.Add("总价（元）", typeof(string));
                foreach (var item in List)
                {
                    var listdel = PayDetail.First(x => x.Key == item);
                    foreach (var item2 in listdel.Value)
                    {
                        dt.Rows.Add(item2.ItemName, item2.Price, item2.Amount, item2.Costs);
                    }
                }
                dataGridView2.DataSource = dt;
                int index = 0;
                dataGridView2.Columns[index].HeaderText = "项目";
                dataGridView2.Columns[index].Width = 250;

                index++;
                dataGridView2.Columns[index].HeaderText = "单价（元）";
                dataGridView2.Columns[index].Width = 100;

                index++;
                dataGridView2.Columns[index].HeaderText = "数量";
                dataGridView2.Columns[index].Width = 100;

                index++;
                dataGridView2.Columns[index].HeaderText = "总价";
                dataGridView2.Columns[index].Width = 100;

                //MessageBox.Show(str.ToString());

            }
        }



        private void DgInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0)
                {
                    //DataGridViewColumn column = dgInfo.Columns[e.RowIndex];
                    if (dataGridView1.Rows[e.RowIndex].Cells[0] == null || Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["选择"].Value) == false)
                    {
                        var isSelct = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
                        dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;
                    }
                    else
                    {
                        dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
                    }
                    var selectGridVew = dataGridView1.Rows.OfType<DataGridViewRow>().ToList().FindAll(t => Convert.ToBoolean(t.Cells["选择"].Value) == true).ToList();
                    if (selectGridVew.Count > 0)
                    {
                        var sumMoney = selectGridVew.Sum(x => Convert.ToDecimal(x.Cells[6].Value));
                        if (sumMoney == 0)
                            textBoxPayAmount.Text = "0";
                        else
                            textBoxPayAmount.Text = (sumMoney - Convert.ToDecimal(Balance.Text)).ToString();

                        List<string> List = new List<string>();
                        foreach (var item in selectGridVew)
                        {
                            string str = item.Cells["处方号"].Value.ToString();
                            List.Add(str);
                        }
                        dataGridView2.Visible = true;
                        DataTable dt = new DataTable();
                        //dt.Columns.Add("id", typeof(string));
                        dt.Columns.Add("项目", typeof(string));
                        dt.Columns.Add("单价（元）", typeof(string));
                        dt.Columns.Add("数量", typeof(string));
                        dt.Columns.Add("总价（元）", typeof(string));
                        foreach (var item in List)
                        {
                            var listdel = PayDetail.First(x => x.Key == item);
                            foreach (var item2 in listdel.Value)
                            {
                                dt.Rows.Add(item2.ItemName, item2.Price, item2.Amount, item2.Costs);
                            }
                        }
                        dataGridView2.DataSource = dt;
                        int index = 0;
                        dataGridView2.Columns[index].HeaderText = "项目";
                        dataGridView2.Columns[index].Width = 250;

                        index++;
                        dataGridView2.Columns[index].HeaderText = "单价（元）";
                        dataGridView2.Columns[index].Width = 100;

                        index++;
                        dataGridView2.Columns[index].HeaderText = "数量";
                        dataGridView2.Columns[index].Width = 100;

                        index++;
                        dataGridView2.Columns[index].HeaderText = "总价";
                        dataGridView2.Columns[index].Width = 100;
                    }
                    else
                    {
                        textBoxPayAmount.Text = "0";
                        dataGridView2.DataSource = new DataTable();
                    }
                }
            }
            catch
            {
                MessageBox.Show("获取选中行失败");
            }
        }

        #region   相关控件事件


        private void button5_Click(object sender, EventArgs e)
        {
            if (IsSelect == "1")
            {
                string ListStr = "";
                decimal ToMoney = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    var boolStr = dataGridView1.Rows[i].Cells["选择"].Value.ToString();
                    if (boolStr == "True")
                    {
                        //item.Cells["处方号"].Value.ToString();
                        ToMoney += Convert.ToDecimal(dataGridView1.Rows[i].Cells["处方金额"].Value.ToString());
                        dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
                        ListStr += dataGridView1.Rows[i].Cells["处方号"].Value.ToString() + ",";
                    }
                    else
                    {
                        dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
                    }
                }
                if (!string.IsNullOrEmpty(ListStr))
                {
                    DialogResult dr = MessageBox.Show("选定处方条数" + dataGridView1.Rows.Count + "处方号：" + ListStr + "确定是否计算所选的处方。", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dr == DialogResult.OK)
                    {
                        if (ToMoney == 0)
                        {
                            textBoxPayAmount.Text = "0";
                        }
                        else
                        {
                            textBoxPayAmount.Text = (ToMoney - Convert.ToDecimal(Balance.Text)).ToString();
                        }

                    }
                }
                else
                {
                    textBoxPayAmount.Text = "0";
                    MessageBox.Show("请选择需要计算的处方。");
                }

            }
            else
            {
                var selectGridVew = dataGridView1.Rows.OfType<DataGridViewRow>().ToList();
                if (selectGridVew.Count > 0)
                {
                    string orderNo = "";
                    foreach (var item in selectGridVew)
                    {
                        orderNo += item.Cells[0].Value + ",";
                    }
                    DialogResult dr = MessageBox.Show("选定处方条数" + selectGridVew.Count + "处方号：" + orderNo + "确定是否计算所选的处方。", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dr == DialogResult.OK)
                    {
                        var sumMoney = selectGridVew.Sum(x => Convert.ToDecimal(x.Cells[5].Value));
                        if (sumMoney == 0)
                            textBoxPayAmount.Text = "0";
                        else
                            textBoxPayAmount.Text = (sumMoney - Convert.ToDecimal(Balance.Text)).ToString();
                    }
                }
                else
                {
                    textBoxPayAmount.Text = "0";
                    MessageBox.Show("请选择需要计算的处方。");
                }
            }



        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {

            string time = Convert.ToDateTime(this.dateTimePicker1.Text).ToString("yyyy-MM-dd");
            cmd.ShowOpaqueLayer(this, 100, true);
            lblwaittip.Visible = false;
            this.pictureBox1.Visible = false;
            this.OutTradeNo.Text = "";
            string str = patinfo.CardNO;
            this.textBoxPayAmount.Text = "0";
            queryDate = time;
            threadQueryPatient = new Thread(new ParameterizedThreadStart(DoWork));
            threadQueryPatient.Start(str); // 直接传递参数给DoWork方法
            //MessageBox.Show(time);
        }

        public DateTime getNowDateTime()
        {
            DateTime date = DateTime.Now;
            try
            {
                ServiceRef.ResultBase resTime = new ServiceRef.ResultBase();
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                resTime = clientService.QueryHISTime("001", "");
                if (resTime.Result == "0")
                {
                    date = DateTime.Parse(resTime.ReturnValue);
                }
            }
            catch (Exception)
            {

            }
            return date;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            bt_lis.Visible = false;
            bt_exam.Visible = false;
            //reportUrl = string.Empty;
            tb_reporturl.Text = string.Empty;
            int selectedValue = Convert.ToInt32(comboBox1.SelectedValue); // 如果ValueMember设置正确的话
            EndDate = getNowDateTime().AddDays(-selectedValue).ToString("yyyy-MM-dd");
            cmd.ShowOpaqueLayer(this, 100, true);
            lblwaittip.Visible = false;
            this.pictureBox1.Visible = false;
            this.OutTradeNo.Text = "";
            string str = patinfo.CardNO;
            this.textBoxPayAmount.Text = "0";
            threadQueryPatient = new Thread(new ParameterizedThreadStart(DoWork));
            threadQueryPatient.Start(str); // 直接传递参数给DoWork方法
            //string selectedText = comboBox1.SelectedText; // 或者直接使用 SelectedText 获取显示文本（如果需要）
        }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (patinfo == null || string.IsNullOrEmpty(patinfo.CardNO))
            {
                MessageBox.Show("请先输入卡号查询患者信息！");
                return;
            }
            int selectedValue = Convert.ToInt32(comboBox1.SelectedValue); // 如果ValueMember设置正确的话
            EndDate = getNowDateTime().AddDays(-selectedValue).ToString("yyyy-MM-dd");
            cmd.ShowOpaqueLayer(this, 100, true);
            lblwaittip.Visible = false;
            this.pictureBox1.Visible = false;
            this.OutTradeNo.Text = "";
            string str = patinfo.CardNO;
            this.textBoxPayAmount.Text = "0";
            threadQueryPatient = new Thread(new ParameterizedThreadStart(DoWork));
            threadQueryPatient.Start(str); // 直接传递参数给DoWork方法
        }


        #endregion
        #endregion

        #region ---------------------------状态查询-----------------------
        int payStateRes = -1;
        public string PayStateMsg = "";
        private Thread threadpayStateQuery;
        public delegate void FormShowpayStateQuery();
        public FormShowpayStateQuery invokepayStateQuery;
        /// <summary>
        /// 状态查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click_payStateQuery(object sender, EventArgs e)
        {
            try
            {
                /*
                // 等待OutTradeNo值生成完成，最多等待3秒
                int maxWaitTime = 10000; // 最大等待时间10秒
                int waitInterval = 200; // 每次等待间隔100毫秒
                int totalWaitTime = 0;
                
                // 循环等待直到OutTradeNo有值或超时
                while (string.IsNullOrEmpty(this.OutTradeNo.Text) && totalWaitTime < maxWaitTime)
                {
                    System.Threading.Thread.Sleep(waitInterval);
                    totalWaitTime += waitInterval;
                    // 处理UI消息，避免界面假死
                    Application.DoEvents();
                }
                */
                // 检查最终状态
                if (string.IsNullOrEmpty(this.OutTradeNo.Text))
                {
                    //MessageBox.Show("未生成订单，请先生成订单");
                    return;
                }
                
                cmd.ShowOpaqueLayer(this, 100, true);
                threadpayStateQuery = new Thread(payStateQuery);
                threadpayStateQuery.Start(); // 直接传递参数给DoWork方法
            }
            catch
            {
                MessageBox.Show("生成订单异常");
            }
        }

        void payStateQuery()
        {
            payStateRes = -999;
            PayStateMsg = "";
            try
            {
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                QRPayQueryInput requreInput = new QRPayQueryInput();
                requreInput.OutTradeNo = this.OutTradeNo.Text;
                requreInput.TradeNo = "";
                requreInput.PayMoney = this.textBoxPayAmount.Text;
                requreInput.Terminal = "001";
                requreInput.FacePay = false;
                if (DetectPaymentType(textBoxFKM.Text) == "Alipay")
                {
                    requreInput.PayType = EnumQRPay.alipay;
                }
                else
                {
                    requreInput.PayType = EnumQRPay.weixin;
                }
                operateLog.WriteLog("查询订单支付状态开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("订单号：" + requreInput.OutTradeNo);
                QRPayQueryOutput outputQueryState = clientService.QRPayQueryRequest(requreInput);
                if (outputQueryState.Result != null && outputQueryState.Result == "0")
                {
                    if (!string.IsNullOrEmpty(outputQueryState.OutTradeNo) && !string.IsNullOrEmpty(outputQueryState.TradeNo))
                    {
                        sqlServer.UpdateOrderMsg(patinfo.PatientID, requreInput.OutTradeNo, outputQueryState.TradeNo, getNowDateTime().ToString("yyyy-MM-dd HH:mm:ss"), "1", userData.user_id);
                        string Balance = "";
                        int res = deposit_userDeposit(outputQueryState, ref Balance);
                        if (res == 0)
                        {
                            sqlServer.AddrechargeMsg(patinfo.PatientID, patinfo.PatientName, patinfo.PatientIDCardNO, requreInput.OutTradeNo, outputQueryState.TotalAmount, outputQueryState.TradeNo, userData.user_id);
                            string IsPrint = ConfigurationManager.AppSettings["IsPrint"].ToString();
                            if (IsPrint == "1")
                            {
                                PrintPt(outputQueryState.TotalAmount, outputQueryState.OutTradeNo, outputQueryState.TradeNo, getNowDateTime().ToString("yyyy-MM-dd HH:mm:ss"), Balance);
                            }
                            PayStateMsg = Balance;
                            payStateRes = 0;
                        }
                        else
                        {
                            sqlServer.UpdateOrderMsg(patinfo.PatientID, requreInput.OutTradeNo, outputQueryState.TradeNo, getNowDateTime().ToString("yyyy-MM-dd HH:mm:ss"), "2", userData.user_id);
                            PayStateMsg = "收款成功，但充值失败！";
                            payStateRes = -1;
                        }

                    }
                    else
                    {
                        PayStateMsg = "查询支付状态成功：未支付";
                        payStateRes = -1;
                    }


                }
                else
                {
                    PayStateMsg = "状态查询失败！" + outputQueryState.Message;
                    payStateRes = -1;
                }
            }
            catch
            {
                PayStateMsg = "查询失败！异常";
                payStateRes = -1;
            }
            if (this.Created)
            {
                this.BeginInvoke(this.invokepayStateQuery);
            }
        }

        void updateFromPayStateQuery()
        {
            cmd.HideOpaqueLayer();
            if (payStateRes == 0)
            {
                string msg = "充值后余额：" + PayStateMsg;
                MessageBox.Show("充值成功," + msg);
                textBoxcx.Text = "";
                this.textBoxPayAmount.Text = "0";
                this.textBoxPayAmount.ReadOnly = true;
                this.OutTradeNo.Text = "";
                textBoxFKM.Text = "";
                textBoxcx.Focus();
                //this.OutTradeNo.Text = "";
                //MessageBox.Show("充值成功");
            }
            else
            {
                MessageBox.Show(PayStateMsg);
            }
        }
        #endregion

        /// <summary>
        /// 门诊充值
        /// </summary>
        /// <param name="outputQueryState"></param>
        /// <returns></returns>
        public int deposit_userDeposit(QRPayQueryOutput outputQueryState, ref string Balance)
        {
            try
            {
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();

                ServiceRef.DoPrepayIn inDeposit = new ServiceRef.DoPrepayIn();
                inDeposit.Key = "001";
                string Serial = "";
                ServiceRef.ResultBase reslut = new ServiceRef.ResultBase();
                reslut = clientService.GenerateSN();
                if (reslut != null)
                {
                    Serial = reslut.ReturnValue.ToString();
                }
                inDeposit.Serial = Serial;
                if (outputQueryState.TradeNo.Substring(0, 4) == "4200")
                {
                    inDeposit.PayMode = "7";
                }
                else
                {
                    inDeposit.PayMode = "6";
                }
                inDeposit.Amount = outputQueryState.TotalAmount; // PaymentAmount;
                inDeposit.CashCount = outputQueryState.TotalAmount; //
                #region 支付信息

                inDeposit.PayAccount = outputQueryState.TotalAmount; //PaymentAmount;
                inDeposit.PosSerial = outputQueryState.TradeNo;
                inDeposit.ReferenceNo = outputQueryState.OutTradeNo;
                #endregion
                //个人信息
                inDeposit.CardNO = patinfo.CardNO;
                inDeposit.PatientIDCardNo = patinfo.PatientName;
                inDeposit.PatientID = patinfo.PatientID;
                inDeposit.PatientName = patinfo.PatientIDCardNO;
                inDeposit.TerminalCode = "001";

                inDeposit.yqId = "";
                operateLog.WriteLog("充值执行开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("患者ID：" + patinfo.PatientID);
                operateLog.WriteLog("患者卡号：" + patinfo.CardNO);
                operateLog.WriteLog("患者姓名：" + patinfo.PatientName);
                operateLog.WriteLog("订单号：" + outputQueryState.TradeNo);
                operateLog.WriteLog("订单金额：" + outputQueryState.TotalAmount);
                operateLog.WriteLog("流水号：" + outputQueryState.OutTradeNo);

                #region //卡类型赋值
                inDeposit.CardTypeID = "1";
                #endregion

                //this.BeginSaveAction();
                ServiceRef.DoPrepayOut payrecArray = clientService.DoPrepay(inDeposit);

                if (payrecArray != null)
                {
                    if (payrecArray.Result == "0")
                    {
                        Balance = payrecArray.Balance;
                        //this.EndSaveAction();
                        //outParam.inPerson.banlance = payrecArray.Balance;
                        //outParam.outDepositRes.accBalance = payrecArray.Balance;
                        //outParam.outDepositRes.serialNo = payrecArray.TranFlow;
                        //outParam.outDepositRes.updateTime = payrecArray.TranTime;

                        return 0;
                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    return -1;
                }
            }
            catch
            {
                return -2;
            }
        }

        #region--------------------付款码支付----------------------

        private Thread threadQRBarCodePay;
        public delegate void FormShowQRBarCodePay();
        public FormShowQRBarCodePay invokeQRBarCodePay;
        int QRBarCodePayRes = -1;
        string QRBarCodePayMsg = "";
        private QRBarPayOutput outputQRBarPayOutput;
        string DMFOutTradeNo;
        /// <summary>
        /// 付款码回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxFKM_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下了回车键
            if (e.KeyCode == Keys.Enter)
            {
                textBoxFKM.Enabled = false;  //增加控件控制避免用户重复输入
                operateLog.WriteLog("记录付款码："+ textBoxFKM.Text);
                this.buttonDMF_Click(sender, e);                
            }
        }
        /// <summary>
        /// 当面付
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDMF_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.textBoxPayAmount.Text))
                {
                    MessageBox.Show("请输入充值金额！");
                    return;
                }
                if (string.IsNullOrEmpty(this.labelhzid.Text))
                {
                    MessageBox.Show("请先查询患者信息，再进行充值！");
                    return;
                }
                if (string.IsNullOrEmpty(patinfo.PatientID))
                {
                    MessageBox.Show("请先查询患者信息，再进行充值！");
                    return;
                }
                if (string.IsNullOrEmpty(this.labelName.Text))
                {
                    MessageBox.Show("请先查询患者信息，再进行充值！");
                    return;
                }
                if (string.IsNullOrEmpty(textBoxFKM.Text))
                {
                    MessageBox.Show("请让患者扫付款码！");
                    return;
                } if (Convert.ToDecimal(this.textBoxPayAmount.Text) <= 0)
                {
                    MessageBox.Show("计算得到金额小于等于0，不允许充值！");
                    return;
                }
                lblwaittip.Visible = false;
                this.pictureBox1.Visible = false;
                this.OutTradeNo.Text = "";
                cmd.ShowOpaqueLayer(this, 100, true);
                threadQRBarCodePay = new Thread(QRBarCodePayRequest);
                threadQRBarCodePay.Start(); // 直接传递参数给DoWork方法

            }
            catch
            {
                MessageBox.Show("失败！异常");
            }

        }

        public static string DetectPaymentType(string authCode)
        {
            int payType = int.Parse(authCode.Substring(0, 2));
            int length = authCode.Length;

            if (payType >= 10 && payType <= 15 && length == 18)
                return "WeChat";
            else if (payType >= 25 && payType <= 30 && length >= 16 && length <= 24)
                return "Alipay";
            else
                return "WeChat";
        }
        void QRBarCodePayRequest()
        {
            QRBarCodePayRes = -999;
            DMFOutTradeNo = "";
            ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
            string OutTradeNo = "";
            ServiceRef.ResultBase reslut = new ServiceRef.ResultBase();
            reslut = clientService.GenerateSN();
            if (reslut != null)
            {
                OutTradeNo = reslut.ReturnValue.ToString();
                DMFOutTradeNo = OutTradeNo;
                this.BeginInvoke(new Action(() => this.OutTradeNo.Text = DMFOutTradeNo));// = DMFOutTradeNo;
                QRBarPayInput requreInput = new QRBarPayInput()
                {
                    BarCode = textBoxFKM.Text,
                    OutTradeNo = OutTradeNo,
                    Body = "门诊充值",
                    Subject = "门诊充值",
                    TotalAmount = this.textBoxPayAmount.Text,
                    FacePay = false,

                    Terminal = "001",
                    PatientName = this.labelName.Text,
                    IDCardNo = patinfo.PatientIDCardNO,
                    PatientID = patinfo.PatientID,
                    Operation = "门诊充值",
                    CardNo = patinfo.PatientID,
                    SellerName = "",

                    //微信刷脸支付用参数
                    OpenId = "",
                    SubOpenId = "",


                };
                if (DetectPaymentType(textBoxFKM.Text) == "Alipay")
                {
                    requreInput.PayType = EnumQRPay.alipay;
                    //MessageBox.Show("暂不支持支付宝付款码付款！");
                    //return;
                }
                else
                {
                    requreInput.PayType = EnumQRPay.weixin;
                }
                outputQRBarPayOutput = new QRBarPayOutput();
                var sqlData = sqlServer.AddOrderMsg(patinfo.PatientID, patinfo.PatientName, patinfo.PatientIDCardNO, OutTradeNo, requreInput.TotalAmount, patinfo.CardNO, userData.user_id);
                var Str = sqlData;

                operateLog.WriteLog("付款码支付开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("患者ID：" + patinfo.PatientID);
                operateLog.WriteLog("患者卡号：" + patinfo.CardNO);
                operateLog.WriteLog("患者姓名：" + patinfo.PatientName);
                operateLog.WriteLog("订单号：" + requreInput.OutTradeNo);
                operateLog.WriteLog("订单金额：" + requreInput.TotalAmount);

                outputQRBarPayOutput = clientService.QRBarCodePayRequest(requreInput);

                if (outputQRBarPayOutput.Result != null && outputQRBarPayOutput.Result == "0")
                {
                    int queryCount = Convert.ToInt32(ConfigurationManager.AppSettings["queryCount"].ToString());
                    for (int i = 0; i < queryCount; i++)
                    {
                        QRPayQueryInput requreQueryPayState = new QRPayQueryInput();
                        requreQueryPayState.OutTradeNo = OutTradeNo;
                        requreQueryPayState.TradeNo = "";
                        requreQueryPayState.PayMoney = this.textBoxPayAmount.Text;
                        requreQueryPayState.Terminal = "001";
                        requreQueryPayState.FacePay = false;
                        if (DetectPaymentType(textBoxFKM.Text) == "Alipay")
                        {
                            requreQueryPayState.PayType = EnumQRPay.alipay;
                        }
                        else
                        {
                            requreQueryPayState.PayType = EnumQRPay.weixin;
                        }
                        //requreQueryPayState.PayType = EnumQRPay.weixin;
                        QRPayQueryOutput outputQueryState = clientService.QRPayQueryRequest(requreQueryPayState);
                        if (outputQueryState.Result != null && outputQueryState.Result == "0")
                        {
                            if (!string.IsNullOrEmpty(outputQueryState.OutTradeNo) && !string.IsNullOrEmpty(outputQueryState.TradeNo))
                            {
                                sqlServer.UpdateOrderMsg(patinfo.PatientID, requreInput.OutTradeNo, outputQueryState.TradeNo, getNowDateTime().ToString("yyyy-MM-dd HH:mm:ss"), "1", userData.user_id);
                                string Balance = "";
                                int res = deposit_userDeposit(outputQueryState, ref Balance);
                                if (res == 0)
                                {
                                    sqlServer.AddrechargeMsg(patinfo.PatientID, patinfo.PatientName, patinfo.PatientIDCardNO, requreInput.OutTradeNo, outputQueryState.TotalAmount, outputQueryState.TradeNo, userData.user_id);
                                    string IsPrint = ConfigurationManager.AppSettings["IsPrint"].ToString();
                                    if (IsPrint == "1")
                                    {
                                        PrintPt(outputQueryState.TotalAmount, outputQueryState.OutTradeNo, outputQueryState.TradeNo, outputQueryState.PaymentTime, Balance);
                                    }
                                    QRBarCodePayRes = 0;
                                    QRBarCodePayMsg = Balance;
                                    break;
                                }
                                else
                                {
                                    sqlServer.UpdateOrderMsg(patinfo.PatientID, requreInput.OutTradeNo, outputQueryState.TradeNo, getNowDateTime().ToString("yyyy-MM-dd HH:mm:ss"), "2", userData.user_id);

                                    QRBarCodePayMsg = "收款成功，但充值失败！";
                                    QRBarCodePayRes = -1;
                                    break;
                                }

                            }
                            else
                            {
                                QRBarCodePayMsg = "查询支付状态成功：未支付";
                                QRBarCodePayRes = -1;
                                Thread.Sleep(3000);
                            }
                        }
                        else
                        {
                            QRBarCodePayMsg = "状态查询失败！" + outputQueryState.Message;
                            QRBarCodePayRes = -1;
                            Thread.Sleep(3000);
                        }

                    }

                }
                else
                {
                    QRBarCodePayMsg = "付款码支付失败！" + outputQRBarPayOutput.Message;
                    QRBarCodePayRes = -1;
                }
            }
            else
            {
                QRBarCodePayMsg = "获取流水号失败！";
                QRBarCodePayRes = -1;
            }
            if (this.Created)
            {
                this.BeginInvoke(this.invokeQRBarCodePay);
            }
        }

        void updataQRBarCodePay()
        {
            cmd.HideOpaqueLayer();
            this.OutTradeNo.Text = DMFOutTradeNo;

            //在这里恢复文本框可输入状态 
            textBoxFKM.Enabled = true;
            if (QRBarCodePayRes == 0)
            {
                this.OutTradeNo.Text = DMFOutTradeNo;
                string msg = "充值后余额：" + QRBarCodePayMsg;
                MessageBox.Show("充值成功," + msg);
                textBoxcx.Text = "";
                this.textBoxPayAmount.Text = "0";
                this.textBoxPayAmount.ReadOnly = true;
                this.OutTradeNo.Text = "";
                textBoxFKM.Text = "";
                textBoxcx.Focus();
            }
            else
            {
                MessageBox.Show(QRBarCodePayMsg);
                return;
            }
        }

        /// <summary>
        /// 定时器事件处理程序 - 定期刷新数据（每10分钟执行一次）
        /// </summary>
        private void timerDataRefresh_Tick(object sender, EventArgs e)
        {
            try
            {
                AddMessageToList("[数据刷新] 开始执行定时数据刷新任务");
                
                // 在后台线程执行数据刷新任务，避免阻塞UI
                ThreadPool.QueueUserWorkItem(state =>
                {
                    try
                    {
                        // 清空本地数据库
                        bool clearResult = LocalDbHelper.ClearAllData();
                        
                        // 在UI线程更新界面
                        this.Invoke(new MethodInvoker(() =>
                        {
                            AddMessageToList($"[数据刷新] 清空本地数据库结果: {clearResult}");
                            
                            // 刷新数据窗口显示清空后的状态
                            LoadLocalData();
                            
                            // 重新获取医生接诊数据
                            LoadDoctorPatientRecords();
                            
                            AddMessageToList("[数据刷新] 定时数据刷新任务完成");
                        }));
                    }
                    catch
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            AddMessageToList("[数据刷新] 执行数据刷新任务时发生错误");
                        }));
                    }
                });
            }
            catch
            {
                AddMessageToList("[数据刷新] 启动数据刷新任务时发生错误");
            }
        }

        /// <summary>
        /// 定时器事件处理程序 - 定期查询患者数据 mdf
        /// </summary>
        private void timerPatientQuery_Tick(object sender, EventArgs e)
        {
            try
            {
                // 检查是否有用户ID
                if (string.IsNullOrEmpty(userData.user_id))
                {
                    AddMessageToList("[定时查询] 用户ID为空，跳过查询");
                    return;
                }

                // 在后台线程执行查询
                ThreadPool.QueueUserWorkItem(state =>
                {
                    try
                    {
                        var result = PatientDataService.QueryPatientData(userData.user_id);
                        
                        // 在UI线程更新界面
                        this.Invoke(new MethodInvoker(() =>
                        {
                            if (result.Success && result.Data != null)
                            {
                                // 使用TimerTaskDataProcessor处理患者数据
                                try
                                {
                                    // 将查询结果转换为API格式的JSON数据
                                    var apiFormatData = new
                                    {
                                        success = result.Success,
                                        message = result.Message,
                                        data = new
                                        {
                                            outP_VISIT_ID = result.Data.OutpVisitId,
                                            patienT_ID = result.Data.PatientId,
                                            patI_NAME = result.Data.PatientName,
                                            outP_SPECIAL_NAME = result.Data.OutpSpecialName,
                                            outP_DATE = result.Data.OutpDate,
                                            visiT_ID = result.Data.VisitId,
                                            admissioN_DOCTOR = result.Data.AdmissionDoctor,
                                            doctoR_VS_OUTP_VISIT_ID = result.Data.DoctorVsOutpVisitId,
                                            qR_CODE = result.Data.QrCode,
                                            registratioN_FEE_STATUS = result.Data.RegistrationFeeStatus,
                                            paT_LEVEL = result.Data.PatLevel,
                                            liS_COUNT = result.Data.LisCount,
                                            exaM_COUNT = result.Data.ExamCount,
                                            reaD_FLAG = result.Data.ReadFlag,
                                            ordeR_NAMES = result.Data.OrderNames
                                        }
                                    };

                                    if (result.Data.DoctorVsOutpVisitId.Substring(0, 5) == userData.user_id)
                                    {
                                        string jsonData = JsonConvert.SerializeObject(apiFormatData);
                                        bool saveResult = TimerTaskDataProcessor.ProcessPatientData(jsonData);

                                        if (saveResult)
                                        {
                                            AddMessageToList($"[定时查询] 患者数据已保存: {result.Data.PatientName}, 就诊ID: {result.Data.OutpVisitId}");
                                        }
                                        else
                                        {
                                            AddMessageToList($"[定时查询] 患者数据保存失败或数据已存在: {result.Data.PatientName}, 就诊ID: {result.Data.OutpVisitId}");
                                        }

                                        // 无论数据是否保存成功，都刷新数据窗口以确保界面同步
                                        RefreshLocalDataGrid();
                                    }
                                    

                                }
                                catch
                                {
                                    AddMessageToList("[定时查询] 保存数据时发生错误");
                                }
                                
                                // 显示弹出通知
                                //ShowPatientDataNotification(result.Data);
                            }
                            else
                            {
                                AddMessageToList("[定时查询] 未查询到患者数据");
                            }
                        }));
                    }
                    catch
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            AddMessageToList("[定时查询] 查询异常");
                        }));
                    }
                });
            }
            catch
            {
                AddMessageToList("[定时查询] 启动查询时发生错误");
            }
        }

        /// <summary>
        /// 添加消息到lstMessages控件
        /// </summary>
        private void AddMessageToList(string message)
        {
            try
            {
                string timeStamp = DateTime.Now.ToString("HH:mm:ss");
                string formattedMessage = string.Format("[{0}] {1}", timeStamp, message);
                
                if (lstMessages.InvokeRequired)
                {
                    lstMessages.Invoke(new MethodInvoker(() =>
                    {
                        lstMessages.Items.Add(formattedMessage);
                        lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
                        
                        // 限制消息数量，避免内存占用过多
                        if (lstMessages.Items.Count > 100)
                        {
                            lstMessages.Items.RemoveAt(0);
                        }
                    }));
                }
                else
                {
                    lstMessages.Items.Add(formattedMessage);
                    lstMessages.SelectedIndex = lstMessages.Items.Count - 1;
                    
                    // 限制消息数量，避免内存占用过多
                    if (lstMessages.Items.Count > 100)
                    {
                        lstMessages.Items.RemoveAt(0);
                    }
                }
            }
            catch
            {
                // 避免在消息添加过程中出现异常导致程序崩溃
                System.Diagnostics.Debug.WriteLine("添加消息到列表时出错");
            }
        }

        /// <summary>
        /// 显示患者数据通知弹窗
        /// </summary>
        /// <param name="patientData">患者数据</param>
        private void ShowPatientDataNotification(PatientData patientData)
        {
            try
            {
                // 关闭之前未消失的弹窗
                if (currentNotificationForm != null && !currentNotificationForm.IsDisposed)
                {
                    // 使用CloseNotification方法优雅关闭，而不是直接Close
                    currentNotificationForm.CloseNotification();
                    currentNotificationForm = null;
                }
                
                // 创建并显示新的通知弹窗
                currentNotificationForm = new MessageNotificationForm(
                    "就诊通知", 
                    patientData, 
                    NotificationMessageType.Info
                );
                
                // 监听弹窗关闭事件，以便清理引用
                currentNotificationForm.FormClosed += (sender, e) => 
                {
                    if (currentNotificationForm == sender)
                    {
                        currentNotificationForm = null;
                    }
                };
                
                currentNotificationForm.ShowNotification(); // 使用ShowNotification()显示在正确位置
            }
            catch
            {
                AddMessageToList("[通知弹窗] 显示通知时出错");
            }
        }

        #endregion

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                // 获取第一个选中的行
                DataGridViewRow selectedRow = dataGridView1.SelectedRows[0];
                //DataGridViewColumn column = dgInfo.Columns[e.RowIndex];
                if (dataGridView1.Rows[selectedRow.Index].Cells["操作"] == null || Convert.ToBoolean(dataGridView1.Rows[selectedRow.Index].Cells["操作"].Value) == false)
                {
                    var isSelct = dataGridView1.Rows[selectedRow.Index].Cells[1].Value.ToString();
                    dataGridView1.Rows[selectedRow.Index].Cells["操作"].Value = true;
                    //dataGridView1.Rows[selectedRow.Index].DefaultCellStyle.ForeColor = Color.Red;
                    dataGridView1.Rows[selectedRow.Index].Cells["操作"].Style.ForeColor = Color.Blue;
                }
                else
                {
                    dataGridView1.Rows[selectedRow.Index].Cells["操作"].Value = false;
                    //dataGridView1.Rows[selectedRow.Index].DefaultCellStyle.ForeColor = Color.Black;
                    dataGridView1.Rows[selectedRow.Index].Cells["操作"].Style.ForeColor = Color.Black;
                }
                var selectGridVew = dataGridView1.Rows.OfType<DataGridViewRow>().ToList().FindAll(t => Convert.ToBoolean(t.Cells["操作"].Value) == true).ToList();
                if (selectGridVew.Count > 0)
                {
                    var sumMoney = selectGridVew.Sum(x => Convert.ToDecimal(x.Cells["处方金额"].Value));
                    if (sumMoney == 0)
                        textBoxPayAmount.Text = "0";
                    else
                        textBoxPayAmount.Text = (sumMoney - Convert.ToDecimal(Balance.Text)).ToString();

                }
                else
                { textBoxPayAmount.Text = "0"; }
                // 处理选中行的逻辑
                Console.WriteLine("选中的行索引: " + selectedRow.Index);
            }
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            textBoxcx.Focus();
        }

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            //dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = dataGridView1.DefaultCellStyle.BackColor;
            //dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = dataGridView1.DefaultCellStyle.ForeColor;
        }


        private void PrintPt(string money, string orderNo, string lsh, string time, string Balance)
        {
            string printer = "";
            var pd = new PrintDocument();
            pd.PrintController = new StandardPrintController();
            if (!string.IsNullOrEmpty(printer))
            {
                pd.PrinterSettings.PrinterName = printer;
            }
            pd.PrintPage += (sender, e) =>
            {
                var point = new Point(0, 9);
                //bool isPrintQrcode = false;
                FontStyle fontStyle = FontStyle.Regular;
                fontStyle = FontStyle.Bold;
                var font = new Font("仿宋", 8, fontStyle);
                var solidBrush = new SolidBrush(Color.Black);
                var pen = new Pen(Color.Black);
                e.Graphics.DrawString("=========================================", font, solidBrush, new Point(point.X, point.Y));
                e.Graphics.DrawString("=============柳州市妇幼保健院医院门诊充值凭条===========", new Font("仿宋", 10, fontStyle), solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("姓  名：" + patinfo.PatientName + "      性别：" + patinfo.PatientSex, font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("交易金额：" + money + "元", font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("支付方式：微信", font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("交易订单号：" + orderNo, font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("交易流水号：" + lsh, font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("充值后余额：" + Balance, font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("=========================================", font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("交易时间：" + time, font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("交易状态：成功", font, solidBrush, new Point(point.X, point.Y));
                point.Y += 18;
                e.Graphics.DrawString("=========================================", font, solidBrush, new Point(point.X, point.Y));

            };
            pd.Print();

        }

        private void 输入充值金额_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.labelhzid.Text))
            {
                MessageBox.Show("请先查询患者信息，再进行输入充值金额！");
                return;
            }
            this.textBoxPayAmount.Text = "0";
            this.textBoxPayAmount.ReadOnly = false;
            this.textBoxPayAmount.Focus();
        }

        private void textBoxcx_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下了回车键
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    Clipboard.SetText(textBoxcx.Text);
                }
                catch (Exception)
                {

                }
                if (Regex.IsMatch(textBoxcx.Text, @"[\uFF00-\uFFEF]"))
                {
                    MessageBox.Show("输入包含全角符号，请重新输入！", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    // 清空输入框
                    textBoxcx.Text = "";
                }
                else
                {
                    this.button2_Click(sender, e);
                }

            }
        }

        private void textBoxPayAmount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isCheckMsg == false)
                {

                    MessagePrompt from = new MessagePrompt(patinfo);
                    from.Closed += new EventHandler(frmPop_Closed);
                    from.ShowDialog();
                }
                else
                {
                    this.textBoxFKM.Focus();
                }

            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //QRPayRefund("PAY2025031800700359", "4200002634202503184048989592", "0.01");
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            PayMsg from = new PayMsg(userData);
            from.ShowDialog();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            BillSummaryForm from = new BillSummaryForm(userData);
            from.ShowDialog();
        }


        #region ------------------医保电子凭证结算部分-----------------------
        /// <summary>
        /// 待缴费明细列表
        /// </summary>
        public List<ServiceRef.BMS_ORDERS_BILL_DETAILChargeItemItem> payDetailList = new List<ServiceRef.BMS_ORDERS_BILL_DETAILChargeItemItem>();

        [DllImport("NationECCode.dll", EntryPoint = "NationEcTrans")]
        public static extern IntPtr NationEcTrans(StringBuilder strUrl, StringBuilder InData, StringBuilder OutData);

        private string card_code = "";
        private string userInf = "";
        private string ListStr = "";
        private QueryPrePaymentCostOut payres;

        private void btnYbPay_Click(object sender, EventArgs e)
        {
            try
            {
                payDetailList = new List<BMS_ORDERS_BILL_DETAILChargeItemItem>();
                payres = new QueryPrePaymentCostOut();
                card_code = "";
                userInf = "";

                if (string.IsNullOrEmpty(this.labelhzid.Text))
                {
                    MessageBox.Show("请先查询患者信息，再进行充值！");
                    return;
                }
                if (string.IsNullOrEmpty(patinfo.PatientID))
                {
                    MessageBox.Show("请先查询患者信息，再进行充值！");
                    return;
                }
                if (string.IsNullOrEmpty(this.labelName.Text))
                {
                    MessageBox.Show("请先查询患者信息，再进行充值！");
                    return;
                }

                var data = new
                   {
                       data = new
                       {
                           operatorId = "ZJ01",
                           operatorName = "自助机Z001",
                           officeId = "01",
                           officeName = "内科",
                           orgId = "H45020200060",
                           businessType = "01301",
                           deviceType = ""
                       },
                       orgId = "H45112100058",
                       transType = "ec.query"
                   };
                StringBuilder ptrUrl = new StringBuilder();
                StringBuilder ptrSendInfo = new StringBuilder();
                ptrSendInfo.Append(Newtonsoft.Json.JsonConvert.SerializeObject(data));
                StringBuilder OutData = new StringBuilder(8000 + 1);
                ptrUrl.Append("http://59.211.232.33:10110/localcfc/api/hsecfc/localQrCodeQuery");
                NationEcTrans(ptrUrl, ptrSendInfo, OutData);
                string ectrans = OutData.ToString();
                card_code = ectrans;
                var OutDataModel = Newtonsoft.Json.JsonConvert.DeserializeObject<MedicalVoucherRoot>(ectrans);
                if (OutDataModel.code == "0")
                {
                    #region 获取参保信息
                    ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                    var cardInfoIn = new ServiceRef.kite_aio_In();
                    cardInfoIn.cardInfo = "";
                    cardInfoIn.medicareType = "1";
                    cardInfoIn.socialsecurityNo = "";
                    cardInfoIn.card_id = "";
                    cardInfoIn.card_code = ectrans;
                    cardInfoIn.yqId = "";
                    cardInfoIn.terminalCode = "001";
                    cardInfoIn.PatientID = patinfo.PatientID;
                    var result = clientService.kite_aio_co3(cardInfoIn);
                    if (result.Result == "00")
                    {
                        if (result.idCardCode != patinfo.PatientIDCardNO)
                        {
                            MessageBox.Show("当前患者身份证号：" + patinfo.PatientIDCardNO + ",与医保电子凭证参保信息身份证号" + result.idCardCode + "不一致，请使用患者本人医保电子凭证结算！");
                            return;
                        }
                        userInf = result.data;
                        if (IsSelect == "1")
                        {
                            #region 进行预结算
                            QueryPrePaymentCostIn inDoPrePay = new QueryPrePaymentCostIn();
                            inDoPrePay.TerminalCode = "001";
                            inDoPrePay.PatientID = patinfo.PatientID;
                            inDoPrePay.PayType = "1";
                            inDoPrePay.yqId = "LZ001";


                            inDoPrePay.ChargeItem = new List<BMS_ORDERS_BILL_DETAILChargeItemItem>();

                           
                            decimal ToMoney = 0;
                            for (int i = 0; i < dataGridView1.Rows.Count; i++)
                            {
                                var boolStr = dataGridView1.Rows[i].Cells["选择"].Value.ToString();
                                if (boolStr == "True")
                                {
                                    //item.Cells["处方号"].Value.ToString();
                                    ToMoney += Convert.ToDecimal(dataGridView1.Rows[i].Cells["处方金额"].Value.ToString());
                                    dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
                                    ListStr += dataGridView1.Rows[i].Cells["处方号"].Value.ToString() + ",";

                                    var listdel = PayDetail.First(x => x.Key == dataGridView1.Rows[i].Cells["处方号"].Value.ToString());
                                    foreach (var item2 in listdel.Value)
                                    {
                                        ServiceRef.BMS_ORDERS_BILL_DETAILChargeItemItem ChargeItemItem = new ServiceRef.BMS_ORDERS_BILL_DETAILChargeItemItem();
                                        #region 柳州妇幼
                                        ChargeItemItem.ItemId = item2.ItemId;
                                        ChargeItemItem.PatientVisitId = dataGridView1.Rows[i].Cells["就诊id"].Value.ToString();
                                        ChargeItemItem.ClinicItemCode = item2.ClinicItemCode;
                                        ChargeItemItem.SpellCode = item2.SpellCode;
                                        ChargeItemItem.ClinicId = item2.ClinicId;
                                        ChargeItemItem.OrderDate = item2.OrderDate;
                                        ChargeItemItem.OrderBeginDate = item2.OrderBeginDate;
                                        ChargeItemItem.MipsEmpIdBegDoct = item2.MipsEmpIdBegDoct;
                                        ChargeItemItem.DiagIcd = item2.DiagIcd;
                                        ChargeItemItem.DiagName = item2.DiagName;
                                        ChargeItemItem.Diags = item2.Diags;

                                        ChargeItemItem.ItemClass = item2.ItemClass;
                                        ChargeItemItem.ItemClassName = item2.ItemClassName;
                                        ChargeItemItem.ItemCode = item2.ItemCode;
                                        ChargeItemItem.ItemName = item2.ItemName;
                                        ChargeItemItem.Spec = item2.Spec;
                                        ChargeItemItem.Amount = item2.Amount;
                                        ChargeItemItem.VisitId = item2.VisitId;
                                        ChargeItemItem.PatientId = item2.PatientId;
                                        ChargeItemItem.Price = item2.Price;
                                        ChargeItemItem.SalesPrice = item2.SalesPrice;
                                        ChargeItemItem.Costs = item2.Costs;
                                        ChargeItemItem.Charges = item2.Charges;
                                        ChargeItemItem.ApplyId = item2.ApplyId;
                                        ChargeItemItem.OrderByDeptCode = item2.OrderByDeptCode;
                                        ChargeItemItem.OrderByDeptName = item2.OrderByDeptName;
                                        ChargeItemItem.PerformedByDeptCode = item2.PerformedByDeptCode;
                                        ChargeItemItem.PerformedByDeptName = item2.PerformedByDeptName;
                                        ChargeItemItem.DiagEmpId = item2.DiagEmpId;
                                        ChargeItemItem.DiagEmpName = item2.DiagEmpName;
                                        ChargeItemItem.DiagByCode = item2.DiagByCode;
                                        ChargeItemItem.InsuranceType = item2.InsuranceType;
                                        ChargeItemItem.InsurLevelCode = item2.InsurLevelCode;
                                        ChargeItemItem.InsurLevelName = item2.InsurLevelName;
                                        ChargeItemItem.ChargeDate = item2.ChargeDate;
                                        ChargeItemItem.OrgIdHospital = item2.OrgIdHospital;
                                        ChargeItemItem.EnterDate = item2.EnterDate;
                                        ChargeItemItem.InvoicePrintStatus = item2.InvoicePrintStatus;
                                        ChargeItemItem.SubjCode = item2.SubjCode;
                                        ChargeItemItem.UnitName = item2.UnitName;
                                        ChargeItemItem.Factor = item2.Factor;
                                        ChargeItemItem.RetailFactor = item2.RetailFactor;
                                        ChargeItemItem.Quantity = item2.Quantity;
                                        ChargeItemItem.UnitQuantity = item2.UnitQuantity;
                                        ChargeItemItem.InClassOnRcptCode = item2.InClassOnRcptCode;
                                        ChargeItemItem.InClassOnRcptCodeName = item2.InClassOnRcptCodeName;
                                        ChargeItemItem.OutClassOnRcptCode = item2.OutClassOnRcptCode;
                                        ChargeItemItem.OutClassOnRcptCodeName = item2.OutClassOnRcptCodeName;
                                        ChargeItemItem.ApplyClass = item2.ApplyClass;
                                        ChargeItemItem.ApplyClassName = item2.ApplyClassName;
                                        ChargeItemItem.Ratio = item2.Ratio;
                                        ChargeItemItem.AutoRatio = item2.AutoRatio;
                                        ChargeItemItem.ChargedStatus = item2.ChargedStatus;
                                        ChargeItemItem.OrderId = item2.OrderId;
                                        ChargeItemItem.OrderItemDetailId = item2.OrderItemDetailId;
                                        ChargeItemItem.CurrentNursingUnit = item2.CurrentNursingUnit;
                                        ChargeItemItem.ExternalId = item2.ExternalId;
                                        ChargeItemItem.IsCharge = item2.IsCharge;
                                        ChargeItemItem.InOutFlag = item2.InOutFlag;
                                        ChargeItemItem.PerMed = item2.PerMed;
                                        ChargeItemItem.FreqName = item2.FreqName;
                                        ChargeItemItem.Duration = item2.Duration;
                                        ChargeItemItem.MedUnitName = item2.MedUnitName;
                                        ChargeItemItem.FreqUnitName = item2.FreqUnitName;
                                        ChargeItemItem.DurationUnitName = item2.DurationUnitName;
                                        #endregion
                                        inDoPrePay.ChargeItem.Add(ChargeItemItem);

                                        payDetailList.Add(ChargeItemItem);
                                    }

                                }
                                else
                                {
                                    dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
                                }
                            }

                            #endregion
                            if (payDetailList != null && payDetailList.Count > 0)
                            {
                                inDoPrePay.RecipeNO = ListStr.Substring(0, ListStr.Length - 1);

                                inDoPrePay.cardInfo = "";
                                inDoPrePay.medicareType = "2";
                                inDoPrePay.totalMoney = ToMoney.ToString();
                                inDoPrePay.uerInfo = result.data;
                                inDoPrePay.extend = ectrans;
                                payres = clientService.QueryPrePaymentCost(inDoPrePay);
                                if (payres != null)
                                {
                                    if (payres.Result == "0")
                                    {
                                        YbPrePay from = new YbPrePay(payres, patinfo, result.medicalBanlance);
                                        from.Closed += new EventHandler(frmPrePay_Closed);
                                        from.ShowDialog();

                                    }
                                    else if (payres.Result == "-1")
                                    {
                                        MessageBox.Show(payres.Message);
                                        return;
                                    }
                                    else if (payres.Result == "-3" || payres.Message.IndexOf("key为空") != -1)
                                    {

                                        MessageBox.Show("key为空!" + payres.Message);
                                        return;
                                    }
                                    else
                                    {
                                        MessageBox.Show(payres.Message);
                                        return;
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("预结算失败，出参数据为空。");
                                    return;
                                }
                            }
                            else
                            {
                                MessageBox.Show("请选择需要计算的处方。");
                            }

                        }
                        else
                        {
                            MessageBox.Show("请选择需要计算的处方。");
                        }


                    }
                    else
                    {
                        MessageBox.Show("医保电子凭证解码失败！" + OutDataModel.message);
                        return;
                    }

                    #endregion

                }
                else
                {
                    MessageBox.Show("医保电子凭证解码失败！" + OutDataModel.message);
                    return;
                }
            }
            catch
            {
                MessageBox.Show("医保电子凭证解码异常！");
            }
        }

        private void frmPrePay_Closed(object sender, EventArgs e)
        {
            ServiceRef.DoPayOut payresdata = new DoPayOut();
            string msg = "";
            YbPrePay frm = (YbPrePay)sender;
            if (frm.IsJs)//余额充足，直接结算
            {
                int res = pay_userPay(payres, frm.bsje, frm.fkm, ref payresdata,ref msg);
                if (res == 0)
                {
                    MessageBox.Show("结算成功！");
                }
                else
                {
                    MessageBox.Show(msg);
                }
               
            }
            else
            {
                cmd.ShowOpaqueLayer(this, 100, true);
                new Thread(() =>
                {
                    QRBarCodePayRequest2(payres, frm.bsje, frm.fkm); //处理事件
                }).Start(); //启动线程
            }
        }
        public delegate void FormShowQRBarCodePay2();
        public FormShowQRBarCodePay2 invokeQRBarCodePay2;

        void QRBarCodePayRequest2(QueryPrePaymentCostOut payres2, string bsje, string fkm)
        {
            QRBarCodePayRes = -999;
            DMFOutTradeNo = "";
            ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
            string OutTradeNo = "";
            ServiceRef.ResultBase reslut = new ServiceRef.ResultBase();
            reslut = clientService.GenerateSN();
            if (reslut != null)
            {
                OutTradeNo = reslut.ReturnValue.ToString();
                DMFOutTradeNo = OutTradeNo;
                QRBarPayInput requreInput = new QRBarPayInput()
                {
                    BarCode = fkm,
                    OutTradeNo = OutTradeNo,
                    Body = "门诊充值",
                    Subject = "门诊充值",
                    //operatorId = InParam.operatorId,
                    TotalAmount = bsje,
                    FacePay = false,

                    Terminal = "001",
                    PatientName = this.labelName.Text,
                    IDCardNo = patinfo.PatientIDCardNO,
                    PatientID = patinfo.PatientID,
                    Operation = "门诊充值",
                    CardNo = patinfo.PatientID,
                    SellerName = "",

                    //微信刷脸支付用参数
                    OpenId = "",
                    SubOpenId = "",


                };
                if (DetectPaymentType(fkm) == "Alipay")
                {
                    requreInput.PayType = EnumQRPay.alipay;
                }
                else
                {
                    requreInput.PayType = EnumQRPay.weixin;
                }
                outputQRBarPayOutput = new QRBarPayOutput();
                var sqlData = sqlServer.AddOrderMsg(patinfo.PatientID, patinfo.PatientName, patinfo.PatientIDCardNO, OutTradeNo, requreInput.TotalAmount, patinfo.CardNO, userData.user_id);
                var Str = sqlData;

                operateLog.WriteLog("付款码支付开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("患者ID：" + patinfo.PatientID);
                operateLog.WriteLog("患者卡号：" + patinfo.CardNO);
                operateLog.WriteLog("患者姓名：" + patinfo.PatientName);
                operateLog.WriteLog("订单号：" + requreInput.OutTradeNo);
                operateLog.WriteLog("订单金额：" + requreInput.TotalAmount);

                outputQRBarPayOutput = clientService.QRBarCodePayRequest(requreInput);

                if (outputQRBarPayOutput.Result != null && outputQRBarPayOutput.Result == "0")
                {
                    int queryCount = Convert.ToInt32(ConfigurationManager.AppSettings["queryCount"].ToString());
                    for (int i = 0; i < queryCount; i++)
                    {
                        QRPayQueryInput requreQueryPayState = new QRPayQueryInput();
                        requreQueryPayState.OutTradeNo = OutTradeNo;
                        requreQueryPayState.TradeNo = "";
                        requreQueryPayState.PayMoney = this.textBoxPayAmount.Text;
                        requreQueryPayState.Terminal = "001";
                        requreQueryPayState.FacePay = false;
                        //requreQueryPayState.PayType = EnumQRPay.weixin;
                        if (DetectPaymentType(fkm) == "Alipay")
                        {
                            requreQueryPayState.PayType = EnumQRPay.alipay;
                        }
                        else
                        {
                            requreQueryPayState.PayType = EnumQRPay.weixin;
                        }
                        QRPayQueryOutput outputQueryState = clientService.QRPayQueryRequest(requreQueryPayState);
                        if (outputQueryState.Result != null && outputQueryState.Result == "0")
                        {
                            if (!string.IsNullOrEmpty(outputQueryState.OutTradeNo) && !string.IsNullOrEmpty(outputQueryState.TradeNo))
                            {
                                sqlServer.UpdateOrderMsg(patinfo.PatientID, requreInput.OutTradeNo, outputQueryState.TradeNo, getNowDateTime().ToString("yyyy-MM-dd HH:mm:ss"), "1", userData.user_id);
                                string Balance = "";
                                int res = deposit_userDeposit(outputQueryState, ref Balance);
                                if (res == 0)
                                {
                                    sqlServer.AddrechargeMsg(patinfo.PatientID, patinfo.PatientName, patinfo.PatientIDCardNO, requreInput.OutTradeNo, outputQueryState.TotalAmount, outputQueryState.TradeNo, userData.user_id);
                                    string IsPrint = ConfigurationManager.AppSettings["IsPrint"].ToString();
                                    if (IsPrint == "1")
                                    {
                                        PrintPt(outputQueryState.TotalAmount, outputQueryState.OutTradeNo, outputQueryState.TradeNo, outputQueryState.PaymentTime, Balance);
                                    }
                                    QRBarCodePayRes = 0;
                                    QRBarCodePayMsg = Balance;

                                    ServiceRef.DoPayOut payresdata = new DoPayOut();
                                    string msg = "";
                                    res = pay_userPay(payres, bsje, fkm, ref payresdata, ref msg);
                                    if (res == 0)
                                    {
                                        QRBarCodePayRes = 0;
                                        QRBarCodePayMsg = Balance;
                                    }
                                    else
                                    {
                                        QRBarCodePayRes = -2;
                                        QRBarCodePayMsg = msg;
                                    }
                                    break;
                                }
                                else
                                {
                                    sqlServer.UpdateOrderMsg(patinfo.PatientID, requreInput.OutTradeNo, outputQueryState.TradeNo, getNowDateTime().ToString("yyyy-MM-dd HH:mm:ss"), "2", userData.user_id);

                                    QRBarCodePayMsg = "收款成功，但充值失败！";
                                    QRBarCodePayRes = -1;
                                    break;
                                }

                            }
                            else
                            {
                                QRBarCodePayMsg = "查询支付状态成功：未支付";
                                QRBarCodePayRes = -1;
                                Thread.Sleep(3000);
                            }
                        }
                        else
                        {
                            QRBarCodePayMsg = "状态查询失败！" + outputQueryState.Message;
                            QRBarCodePayRes = -1;
                            Thread.Sleep(3000);
                        }
                    }
                }
                else
                {
                    QRBarCodePayMsg = "付款码支付失败！" + outputQRBarPayOutput.Message;
                    QRBarCodePayRes = -1;
                }
            }
            else
            {
                QRBarCodePayMsg = "获取流水号失败！";
                QRBarCodePayRes = -1;
            }
            if (this.Created)
            {
                this.BeginInvoke(this.invokeQRBarCodePay2);
            }
        }

        void updataQRBarCodePay2()
        {
            cmd.HideOpaqueLayer();
            this.OutTradeNo.Text = DMFOutTradeNo;
            if (QRBarCodePayRes == 0)
            {
                this.OutTradeNo.Text = DMFOutTradeNo;
                //string msg = "充值后余额：" + QRBarCodePayMsg;
                MessageBox.Show("医保电子凭证结算成功！");
                textBoxcx.Text = "";
                this.textBoxPayAmount.Text = "0";
                this.textBoxPayAmount.ReadOnly = true;
                this.OutTradeNo.Text = "";
                textBoxFKM.Text = "";
                textBoxcx.Focus();
            }
            else
            {
                MessageBox.Show(QRBarCodePayMsg);
                return;
            }
        }

        /// <summary>
        /// 结算his
        /// </summary>
        /// <returns></returns>
        private int pay_userPay(QueryPrePaymentCostOut payres2, string bsje, string fkm, ref ServiceRef.DoPayOut payresdata, ref string msg)
        {
            int res = -1;
            try
            {
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                ServiceRef.DoPayIn inDoPay = new ServiceRef.DoPayIn();
                inDoPay.CardTypeID = "1";
                inDoPay.PayAmount = payres2.PayAmount;
                #region 支付信息
                var list = new List<ServiceRef.DoPayInItem>();
                //医保卡赋值
                //inDoPay.PactFundAmount = payres2.PactFundAmount;
                //inDoPay.PactSelfAmount = payres2.PactSelfAmount;
                inDoPay.PactNO = "";

                {
                    ServiceRef.DoPayInItem item = new ServiceRef.DoPayInItem();
                    item.PayAmount = payres2.PayAmount;
                    item.PayCardNO = "";
                    item.PayTypeID = "5";// inParam.inPayInfo.type.ToString();
                    item.PayNote = "无";
                    item.PayModeName = "医保卡";
                    list.Add(item);
                }
                //诊疗卡赋值
                if (Convert.ToDecimal(bsje) == 0)
                {
                    ServiceRef.DoPayInItem item = new ServiceRef.DoPayInItem();
                    item.PayAmount = payres2.SelfPayAmount;
                    item.PayTypeID ="2";//inParam.inPayInfo.type.ToString();
                    item.PayNote = "无";
                    item.PayModeName = "就诊卡";
                    list.Add(item);
                }

                //微信赋值
                if (Convert.ToDecimal(bsje) > 0)
                {
                    ServiceRef.DoPayInItem item = new ServiceRef.DoPayInItem();
                    item.PayAmount = bsje;
                    item.PayCardNO = "";
                    item.PayNo = fkm;
                    item.PayTypeID = "7" ;//inParam.inPayInfo.type.ToString();
                    item.OutTradeNo = fkm;
                    item.TradeNo = fkm;
                    item.PayNote = "无";
                    item.PayModeName = "微信";
                    list.Add(item);
                }
               
                #endregion

                inDoPay.PatientID = patinfo.PatientID;
                inDoPay.CardNO = patinfo.CardNO;
                inDoPay.PatientIDCardNo = patinfo.PatientIDCardNO;
                inDoPay.PatientName = patinfo.PatientName;
                inDoPay.PatientCardPassword = "";
                inDoPay.InvoiceNo = "";
                inDoPay.ShouldPay = payres2.PayAmount;//SystemStaticData.tmpPay.payPrescriptionList[0].totalMoney;
                inDoPay.PactFundAmount = payres2.PactFundAmount;
                inDoPay.PactSelfAmount = payres2.PactSelfAmount;
                inDoPay.SelfPayAmount = payres2.SelfPayAmount;


                inDoPay.treatId = payres2.treatId;
                inDoPay.xmlInputText = payres2.InputVisitText;

                inDoPay.extend = card_code ?? "";
                inDoPay.medicareType = "2";
                inDoPay.cardinfo = "";
                inDoPay.uerInfo = userInf ?? "";

                //inDoPay.cardinfo = "B32601150|450200D156000005A601EDA21F4037D9|3|2.0|450200|20161130|FFFFFFFF|421023199310197158|易博文|NEW|";

                inDoPay.ChargeItem = new List<ServiceRef.BMS_ORDERS_BILL_DETAILChargeItemItem>();
                inDoPay.yqId = "LZ001";
                
                    inDoPay.ChargeTypeCode = "";// SystemStaticData.tmpPay.payPrescriptionList[0].FYLXDH;//item.FYLXDH;

                    //foreach (var item2 in item.payDetailList)
                    foreach (var item2 in payDetailList)
                    {
                        ServiceRef.BMS_ORDERS_BILL_DETAILChargeItemItem ChargeItemItem = new ServiceRef.BMS_ORDERS_BILL_DETAILChargeItemItem();
                        #region 柳州妇幼
                        ChargeItemItem.ItemId = item2.ItemId;
                        ChargeItemItem.ClinicItemCode = item2.ClinicItemCode;
                        ChargeItemItem.PatientVisitId = item2.PatientVisitId;
                        ChargeItemItem.SpellCode = item2.SpellCode;
                        ChargeItemItem.ClinicId = item2.ClinicId;
                        ChargeItemItem.OrderDate = item2.OrderDate;
                        ChargeItemItem.OrderBeginDate = item2.OrderBeginDate;
                        ChargeItemItem.MipsEmpIdBegDoct = item2.MipsEmpIdBegDoct;
                        ChargeItemItem.DiagIcd = item2.DiagIcd;
                        ChargeItemItem.DiagName = item2.DiagName;
                        ChargeItemItem.Diags = item2.Diags;

                        ChargeItemItem.ItemClass = item2.ItemClass;
                        ChargeItemItem.ItemClassName = item2.ItemClassName;
                        ChargeItemItem.ItemCode = item2.ItemCode;
                        ChargeItemItem.ItemName = item2.ItemName;
                        ChargeItemItem.Spec = item2.Spec;
                        ChargeItemItem.Amount = item2.Amount;
                        ChargeItemItem.VisitId = item2.VisitId;
                        ChargeItemItem.PatientId = item2.PatientId;
                        ChargeItemItem.Price = item2.Price;
                        ChargeItemItem.SalesPrice = item2.SalesPrice;
                        ChargeItemItem.Costs = item2.Costs;
                        ChargeItemItem.Charges = item2.Charges;
                        ChargeItemItem.ApplyId = item2.ApplyId;
                        ChargeItemItem.OrderByDeptCode = item2.OrderByDeptCode;
                        ChargeItemItem.OrderByDeptName = item2.OrderByDeptName;
                        ChargeItemItem.PerformedByDeptCode = item2.PerformedByDeptCode;
                        ChargeItemItem.PerformedByDeptName = item2.PerformedByDeptName;
                        ChargeItemItem.DiagEmpId = item2.DiagEmpId;
                        ChargeItemItem.DiagEmpName = item2.DiagEmpName;
                        ChargeItemItem.DiagByCode = item2.DiagByCode;
                        ChargeItemItem.InsuranceType = item2.InsuranceType;
                        ChargeItemItem.InsurLevelCode = item2.InsurLevelCode;
                        ChargeItemItem.InsurLevelName = item2.InsurLevelName;
                        ChargeItemItem.ChargeDate = item2.ChargeDate;
                        ChargeItemItem.OrgIdHospital = item2.OrgIdHospital;
                        ChargeItemItem.EnterDate = item2.EnterDate;
                        ChargeItemItem.InvoicePrintStatus = item2.InvoicePrintStatus;
                        ChargeItemItem.SubjCode = item2.SubjCode;
                        ChargeItemItem.UnitName = item2.UnitName;
                        ChargeItemItem.Factor = item2.Factor;
                        ChargeItemItem.RetailFactor = item2.RetailFactor;
                        ChargeItemItem.Quantity = item2.Quantity;
                        ChargeItemItem.UnitQuantity = item2.UnitQuantity;
                        ChargeItemItem.InClassOnRcptCode = item2.InClassOnRcptCode;
                        ChargeItemItem.InClassOnRcptCodeName = item2.InClassOnRcptCodeName;
                        ChargeItemItem.OutClassOnRcptCode = item2.OutClassOnRcptCode;
                        ChargeItemItem.OutClassOnRcptCodeName = item2.OutClassOnRcptCodeName;
                        ChargeItemItem.ApplyClass = item2.ApplyClass;
                        ChargeItemItem.ApplyClassName = item2.ApplyClassName;
                        ChargeItemItem.Ratio = item2.Ratio;
                        ChargeItemItem.AutoRatio = item2.AutoRatio;
                        ChargeItemItem.ChargedStatus = item2.ChargedStatus;
                        ChargeItemItem.OrderId = item2.OrderId;
                        ChargeItemItem.OrderItemDetailId = item2.OrderItemDetailId;
                        ChargeItemItem.CurrentNursingUnit = item2.CurrentNursingUnit;
                        ChargeItemItem.ExternalId = item2.ExternalId;
                        ChargeItemItem.IsCharge = item2.IsCharge;
                        ChargeItemItem.InOutFlag = item2.InOutFlag;
                        ChargeItemItem.PerMed = item2.PerMed;
                        ChargeItemItem.FreqName = item2.FreqName;
                        ChargeItemItem.Duration = item2.Duration;
                        ChargeItemItem.MedUnitName = item2.MedUnitName;
                        ChargeItemItem.FreqUnitName = item2.FreqUnitName;
                        ChargeItemItem.DurationUnitName = item2.DurationUnitName;
                        #endregion
                        inDoPay.ChargeItem.Add(ChargeItemItem);
                    }
               
                inDoPay.RegFlow = ListStr.Substring(0, ListStr.Length - 1); ;

                //inDoPay.RegFlow = SystemStaticData.tmpPay.payPrescriptionList[0].prescriptionNo;
                inDoPay.Serial = DateTime.Now.ToString("yyyyMMddHHmmss");
                inDoPay.TerminalCode = "001";
                inDoPay.Key = "001";
                inDoPay.list = list;
                //this.BeginSaveAction();
                // 记录DoPay调用的入参JSON日志
                operateLog.WriteLog("DoPay调用入参：" + Newtonsoft.Json.JsonConvert.SerializeObject(inDoPay));
                payresdata = clientService.DoPay(inDoPay);
                // 记录DoPay调用的返回值JSON日志
                operateLog.WriteLog("DoPay调用返回值：" + Newtonsoft.Json.JsonConvert.SerializeObject(payresdata));

                if (payres != null)
                {
                    if (payres.Result == "0")
                    {
                        //this.EndSaveAction();
                        //outParam.outPayRes.sn = payres.TranFlow;
                        //outParam.outPayRes.invoiceNo = payres.TranFlow;
                        //outParam.outPayRes.drugWindows = payres.DrugWindows;
                        //outParam.outPayRes.updateTime = payres.TranTime;
                        //outParam.inPerson.banlance = payres.Balance;
                        
                        res = 0;

                    }
                    else if (payres.Result == "-1")
                    {
                        msg ="结算失败！"+ payres.Message;
                        res = - 1;
                    }
                    else if (payres.Result == "-3" || payres.Message.IndexOf("key为空") != -1)
                    {
                        msg = "结算失败！key为空！" + payres.Message;
                        res = - 2;
                    }
                    else
                    {
                        msg = "结算失败！" + payres.Message;
                        res = - 2;
                    }
                }
                else
                {
                    msg = "结算失败！出参信息为空！";
                    res = - 2;
                }
            }
            catch
            {
                msg = "结算his异常";
                res = -2;
            }

            return res;
        }

        #endregion

        // private bool IsMseeg = false; // 已移除未使用的字段

        public delegate void FormShowSetFoucsKH();
        public FormShowSetFoucsKH invokeSetFoucsKH;

        public delegate void FormShowSetFoucs();
        public FormShowSetFoucs invokeSetFoucs;

        private void frmPop_Closed(object sender, EventArgs e)
        {

            MessagePrompt frm = (MessagePrompt)sender;
            if (frm.isOk)
            {
                if (this.Created)
                {
                    this.BeginInvoke(this.invokeSetFoucs);
                }
            }
            else
            {
                if (this.Created)
                {
                    this.BeginInvoke(this.invokeSetFoucsKH);
                }
            }
        }

        public void SetFoucsKH()
        {
            this.textBoxFKM.Text = "";
            this.textBoxcx.Focus();
        }

        public void SetFoucs()
        {
            this.textBoxFKM.Focus();
        }

        private bool isCheckMsg = false;
        private void IsCheckLogin_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void LoginPop_Closed(object sender, EventArgs e)
        {
            LoginJY frm = (LoginJY)sender;
            if (frm.IsLogin)
            {
                if (isCheckMsg == false)
                {
                    IsCheckLogin.Checked = true;
                    isCheckMsg = true;
                }
                else
                {
                    IsCheckLogin.Checked = false;
                    isCheckMsg = false;
                }
            }
            else
            {
                if (isCheckMsg == false)
                {
                    IsCheckLogin.Checked = false;
                    isCheckMsg = false;
                }
                else
                {
                    IsCheckLogin.Checked = true;
                    isCheckMsg = true;
                }
            }
        }

        private void IsCheckLogin_Click(object sender, EventArgs e)
        {
            LoginJY login = new LoginJY(userData.user_id);
            login.Closed += new EventHandler(LoginPop_Closed);
            login.ShowDialog();
        }

        private void textBoxFKM_Click(object sender, EventArgs e)
        {
            //if (isCheckMsg == false)
            //{

            //    MessagePrompt from = new MessagePrompt(patinfo);
            //    from.Closed += new EventHandler(frmPop_Closed);
            //    from.ShowDialog();
            //}
        }

        private void bt_queryPatVisitList_Click(object sender, EventArgs e)
        {
            try
            {
                string _url = ConfigurationManager.AppSettings["hisUrl"].ToString() + "His/getPatVistListByEmp";
                string _Parm = "{\"user_id\":\"" + userData.user_id + "\"}";
                string _resultJson = CodeHelper.HttpPostJson(_url, _Parm);
                if (_resultJson != "[]")
                {
                    List<Dictionary<string, object>> data = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(_resultJson);
                    DGV_PatVisitList.Rows.Clear();
                    foreach (var row in data)
                    {
                        int rowIndex = DGV_PatVisitList.Rows.Add();
                        foreach (var column in row)
                        {
                            if (DGV_PatVisitList.Columns.Contains(column.Key))
                            {
                                DGV_PatVisitList.Rows[rowIndex].Cells[column.Key].Value = column.Value;
                            }
                            //DGV_PatVisitList.Rows[rowIndex].Cells[column.Key].Value = column.Value;
                        }
                    }
                }
                if (DGV_PatVisitList != null)
                {
                    DGV_PatVisitList.ClearSelection();
                    // 订阅 CellFormatting 事件
                    DGV_PatVisitList.CellFormatting += DGV_PatVisitList_CellFormatting;
                    // 订阅 CellContentClick 事件，用于处理按钮点击
                    DGV_PatVisitList.CellContentClick += DGV_PatVisitList_CellContentClick;
                    // 将 lis_count 和 exam_count 列转换为按钮列
                    ConvertColumnToButtonColumn("lis_count");
                    ConvertColumnToButtonColumn("exam_count");

                }
            }
            catch
            {
                MessageBox.Show("发生错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //throw ex;
            }
        }

        private void ConvertColumnToButtonColumn(string columnName)
        {
            try
            {
                // 检查 DGV_PatVisitList 是否为空
                if (DGV_PatVisitList == null)
                {
                    MessageBox.Show("DGV_PatVisitList 控件未正确初始化");
                    return;
                }

                // 检查列是否存在
                if (!DGV_PatVisitList.Columns.Contains(columnName))
                {
                    MessageBox.Show("列 " + columnName + " 不存在于 DGV_PatVisitList 中");
                    return;
                }

                int columnIndex = DGV_PatVisitList.Columns[columnName].Index;
                DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
                buttonColumn.Name = columnName;
                buttonColumn.HeaderText = DGV_PatVisitList.Columns[columnIndex].HeaderText;

                // 保存原列的值
                object[] values = new object[DGV_PatVisitList.Rows.Count];
                for (int i = 0; i < DGV_PatVisitList.Rows.Count; i++)
                {
                    values[i] = DGV_PatVisitList.Rows[i].Cells[columnIndex].Value;
                }

                // 移除原列
                DGV_PatVisitList.Columns.RemoveAt(columnIndex);

                // 再次检查索引是否有效
                if (columnIndex < 0 || columnIndex > DGV_PatVisitList.Columns.Count)
                {
                    columnIndex = DGV_PatVisitList.Columns.Count; // 如果越界，插入到最后
                }

                // 插入新的按钮列
                DGV_PatVisitList.Columns.Insert(columnIndex, buttonColumn);
                // 恢复原列的值
                for (int i = 0; i < DGV_PatVisitList.Rows.Count; i++)
                {
                    DGV_PatVisitList.Rows[i].Cells[columnIndex].Value = values[i];
                }
            }
            catch
            {
                MessageBox.Show("转换列 " + columnName + " 时出现错误");
            }
        }

        private void DGV_PatVisitList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridView dataGridView = (DataGridView)sender;
                DataGridViewRow row = dataGridView.Rows[e.RowIndex];

                // 找到 order_names 列的索引
                if (dataGridView.Columns.Contains("order_names"))
                {
                    int orderNamesColumnIndex = dataGridView.Columns["order_names"].Index;
                    DataGridViewCell orderNamesCell = row.Cells[orderNamesColumnIndex];

                    if (orderNamesCell.Value != null)
                    {
                        string cellValue = orderNamesCell.Value.ToString();
                        if (cellValue.Contains("已计费"))
                        {
                            // 使用浅绿颜色
                            row.DefaultCellStyle.BackColor = Color.LightGreen;
                        }
                        else if (cellValue.Contains("未计费"))
                        {
                            row.DefaultCellStyle.BackColor = Color.Red;
                        }
                        else if (cellValue.Contains("未开诊查费"))
                        {
                            row.DefaultCellStyle.BackColor = Color.Yellow;
                        }
                        else
                        {
                            // 恢复默认颜色
                            row.DefaultCellStyle.BackColor = SystemColors.Window;
                        }
                    }
                }
            }
        }

        private void DGV_PatVisitList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dataGridView = (DataGridView)sender;
            if (e.RowIndex >= 0 && (dataGridView.Columns[e.ColumnIndex].Name == "lis_count" || dataGridView.Columns[e.ColumnIndex].Name == "exam_count"))
            {
                DataGridViewCell cell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                if (cell.Value != null)
                {
                    string value = cell.Value.ToString();
                    if (dataGridView.Columns.Contains("id") && value != "0")
                    {
                        int idColumnIndex = dataGridView.Columns["id"].Index;
                        DataGridViewCell idCell = dataGridView.Rows[e.RowIndex].Cells[idColumnIndex];
                        if (idCell.Value != null)
                        {
                            string idValue = idCell.Value.ToString();
                            // 在这里可以使用获取到的 id 值进行后续处理
                            string _url = ConfigurationManager.AppSettings["hisUrl"].ToString() + "His/getQueryUrl?query_id=" + idValue;
                            string _viewUrl = CodeHelper.HttpGetJson(_url);
                            //MessageBox.Show(_viewUrl);
                            string[] browserPaths = {
                                @"C:\Program Files\Google\Chrome\Application\chrome.exe",
                                @"C:\Documents and Settings\Administrator\Application Data\360se6\Application\360se.exe",
                                @"D:\Chrome109.0.5414.120_32\App\Chrome-bin\109.0.5414.120\chrome.exe",
                                @"C:\Users\Administrator\AppData\Roaming\360se6\Application\360se.exe"
                            };
                            string resolution = "1280x720";
                            foreach (string path in browserPaths)
                            {
                                if (System.IO.File.Exists(path))
                                {
                                    try
                                    {
                                        ProcessStartInfo startInfo = new ProcessStartInfo
                                        {
                                            FileName = path,
                                            Arguments = "--window-size=" + resolution + " " + _viewUrl
                                        };
                                        Process.Start(startInfo);
                                        break;
                                    }
                                    catch
                                    {
                                        MessageBox.Show("打开浏览器时出现错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                            }
                        }
                    }
                    // 在这里添加按钮点击后的处理逻辑
                    //MessageBox.Show("你点击了报告数为 " + value + " 的按钮");

                }
            }
        }

        // 已删除重复的Form1_FormClosing方法，使用OnFormClosing方法处理窗体关闭事件

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // 显示本机IP地址
                this.DisplayIPAddress();
                
                // 获取系统信息并发送到服务器
                //try
                //{
                    //string systemInfo = SystemInfoHelper.GetSystemInfo();
                    
                    // 发送系统信息到服务器
                    //SystemInfoResponse response = SystemInfoService.SendSystemInfo(systemInfo);
                    
                    //if (response.Success)
                    //{
                        // 成功发送到服务器
                        //MessageBox.Show($"系统信息已成功发送到服务器\n\n响应消息: {response.Message}", "系统信息上传成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //}
                    //else
                    //{
                        // 发送失败，显示错误信息
                        //MessageBox.Show($"系统信息发送失败\n\n错误信息: {response.Message}\n\n系统信息:\n{systemInfo}", "系统信息上传失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                   // }
                //}
                //catch (Exception ex)
                //{
                    //MessageBox.Show($"获取或发送系统信息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
               // }

                // 异步执行耗时操作，避免阻塞UI线程
                //Thread softwareThread = new Thread(() => {
                //    try
                //    {
                //        // 获取已安装软件列表并显示
                //        string softwareListJson = InstalledSoftwareHelper.GetInstalledSoftwareJson();
                //        //string s = string.Empty;
                //        //MessageBox.Show(softwareListJson.Substring(0,1500));
                //        // 显示软件列表信息（用于测试）
                //        //this.Invoke(new MethodInvoker(() => {
                //        //    MessageBox.Show($"已安装软件列表获取完成！\n\n权限状态: {(InstalledSoftwareHelper.IsRunningAsAdministrator() ? "管理员权限" : "普通用户权限")}\n\n点击确定查看详细JSON数据", "软件列表获取结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //        //    
                //        //    // 显示详细的JSON数据
                //        //    MessageBox.Show(softwareListJson, "软件列表JSON数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //        //}));
                //    }
                //    catch (Exception ex)
                //    {
                //        this.Invoke(new MethodInvoker(() => {
                //            MessageBox.Show($"获取软件列表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //        }));
                //    }
                //});
                //softwareThread.IsBackground = true;
                //softwareThread.Start();
                
                // 异步执行USB控制器操作
                Thread usbThread = new Thread(() => {
                    try
                    {
                        // 使用USB控制器禁用USB存储设备
                        //var result = Login.Instance.UsbController.EnableUsbStorageDevices(); //DisableUsbStorageDevices();
                        //MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().Location);
                        var result = Login.Instance.UsbController.DisableUsbStorageDevices();
                        if (!result.Success)
                        {
                            //this.Invoke(new MethodInvoker(() => {
                            //    MessageBox.Show(result.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            //}));
                        }
                    }
                    catch
                    {
                        // 记录错误但不显示，避免影响用户体验
                        System.Diagnostics.Debug.WriteLine("USB控制器操作失败");
                    }
                });
                usbThread.IsBackground = true;
                usbThread.Start();
                
                // 清空本地数据库
                bool clearResult = LocalDbHelper.ClearAllData();
                Console.WriteLine($"清空本地数据库结果: {clearResult}");
                
                // 刷新数据窗口显示清空后的状态
                LoadLocalData();
                
                // 调用GetDoctorPatientRecords接口获取数据
                LoadDoctorPatientRecords();
                
                // 启动患者数据查询定时器
                if (timerPatientQuery != null)
                {
                    timerPatientQuery.Start(); //暂时屏蔽待测试成功再启用
                }
                
                // 启动数据刷新定时器（每10分钟执行一次）
                if (timerDataRefresh != null)
                {
                    timerDataRefresh.Start();
                    AddMessageToList("[系统] 数据刷新定时器已启动，每10分钟执行一次");
                }
            }
            catch
            {
                //MessageBox.Show("禁用 USB 移动存储设备时发生错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region USB存储设备控制功能
        private void DisableUSBStorageDevices()
        {
            try
            {
                var result = Login.Instance.UsbController.DisableUsbStorageDevices();
                if (result.Success)
                {
                    //MessageBox.Show("已成功禁用 USB 移动存储设备。\n此设置将在重启后完全生效。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    //MessageBox.Show("禁用 USB 移动存储设备失败。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                //MessageBox.Show("禁用 USB 移动存储设备时发生错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void EnableUSBStorageDevices()
        {
            try
            {
                var result = Login.Instance.UsbController.EnableUsbStorageDevices();
                if (result.Success)
                {
                    //MessageBox.Show("已成功启用 USB 移动存储设备。\n此设置将在重启后完全生效。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    //MessageBox.Show("启用 USB 移动存储设备失败。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                //MessageBox.Show("启用 USB 移动存储设备时发生错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion


        // 窗体关闭时释放资源（已移至系统托盘功能中）
        #region 消息推送客户端代码
        // 消息推送功能已重构到MessagePushClient类中


        #endregion 


        #region 检查检验互认核心业务代码
        /// <summary>
        /// 查阅检查检验互认结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openLisExamWebView(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tb_reporturl.Text))
            {
                //打开内建浏览器，打开reportUrl查阅检查检验互认结果
                string[] browserPaths = {
                                @"C:\Program Files\Google\Chrome\Application\chrome.exe",
                                @"C:\Documents and Settings\Administrator\Application Data\360se6\Application\360se.exe",
                                @"D:\Chrome109.0.5414.120_32\App\Chrome-bin\109.0.5414.120\chrome.exe",
                                @"C:\Users\Administrator\AppData\Roaming\360se6\Application\360se.exe"
                            };
                string resolution = "1280x720";
                foreach (string path in browserPaths)
                {
                    if (System.IO.File.Exists(path))
                    {
                        try
                        {
                            ProcessStartInfo startInfo = new ProcessStartInfo
                            {
                                FileName = path,
                                Arguments = "--window-size=" + resolution + " " + tb_reporturl.Text
                            };
                            Process.Start(startInfo);
                            break;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("打开浏览器时出现错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }
        #endregion

        #region 系统托盘功能
        /// <summary>
        /// 初始化系统托盘图标
        /// </summary>
        private void InitializeSystemTray()
        {
            try
            {
                // 创建托盘右键菜单
                trayContextMenu = new ContextMenuStrip();
                trayContextMenu.Items.Add("显示主窗口", null, ShowMainWindow_Click);
                trayContextMenu.Items.Add("-"); // 分隔线
                trayContextMenu.Items.Add("退出程序", null, ExitApplication_Click);
                
                // 创建系统托盘图标
                notifyIcon = new NotifyIcon()
                {
                    Icon = this.Icon ?? SystemIcons.Application, // 使用窗体图标或默认图标
                    Text = "门诊充值计费程序",
                    Visible = true,
                    ContextMenuStrip = trayContextMenu
                };
                
                // 绑定托盘图标事件
                notifyIcon.DoubleClick += NotifyIcon_DoubleClick;
                notifyIcon.BalloonTipClicked += NotifyIcon_BalloonTipClicked;
                
                // 消息接收事件已在构造函数中订阅
            }
            catch
            {
                MessageBox.Show("初始化系统托盘时发生错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 消息接收事件处理 - 已注释
        /// </summary>
        /// <param name="message">消息模型</param>
        /*
        private void OnMessageReceived(MessageModel message)
        {
            try
            {
                string messageContent = message.Content ?? "无内容";
                string messageTypeText = message.Type.ToString();
                
                // 调试信息
                Console.WriteLine($"收到{messageTypeText}消息: {messageContent}");
                
                // 根据消息类型处理
                switch (message.Type)
                {
                    case MessageType.Chat:
                        // 聊天消息
                        if (notifyIcon != null)
                        {
                            notifyIcon.ShowBalloonTip(3000, "新聊天消息", messageContent, ToolTipIcon.Info);
                        }
                        ShowMessageNotification("聊天消息", messageContent, NotificationMessageType.Info);
                        break;
                        
                    case MessageType.Broadcast:
                        // 广播消息
                        if (notifyIcon != null)
                        {
                            notifyIcon.ShowBalloonTip(5000, "系统广播", messageContent, ToolTipIcon.Warning);
                        }
                        ShowMessageNotification("系统广播", messageContent, NotificationMessageType.Warning);
                        break;
                        
                    case MessageType.Error:
                        // 错误消息
                        if (notifyIcon != null)
                        {
                            notifyIcon.ShowBalloonTip(3000, "错误", messageContent, ToolTipIcon.Error);
                        }
                        ShowMessageNotification("错误", messageContent, NotificationMessageType.Error);
                        break;
                        
                    case MessageType.UserStatusUpdate:
                        // 用户状态更新
                        Console.WriteLine($"用户状态更新: {messageContent}");
                        break;
                        
                    case MessageType.Heartbeat:
                        // 心跳消息，通常不需要显示给用户
                        Console.WriteLine("收到心跳消息");
                        break;
                        
                    default:
                        // 其他类型消息
                        if (notifyIcon != null)
                        {
                            notifyIcon.ShowBalloonTip(3000, "新消息", messageContent, ToolTipIcon.Info);
                        }
                        ShowMessageNotification("新消息", messageContent, NotificationMessageType.Info);
                        break;
                }
            }
            catch
            {
                // 记录错误但不影响主程序运行
                Console.WriteLine("处理消息通知时发生错误");
                MessageBox.Show("处理消息通知时发生错误", "错误");
            }
        }
        */
        
        /// <summary>
        /// 显示消息通知窗体
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="message">消息内容</param>
        /// <param name="messageType">消息类型</param>
        private void ShowMessageNotification(string title, string message, NotificationMessageType messageType)
        {
            try
            {
                // 在UI线程中创建和显示通知窗体
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => ShowMessageNotification(title, message, messageType)));
                    return;
                }
                
                var notificationForm = new MessageNotificationForm(title, message, messageType);
                
                // 设置自定义按钮
                notificationForm.SetActionButtons("查看详情", "忽略");
                
                // 订阅事件
                notificationForm.ActionButtonClicked += (sender, e) =>
                {
                    if (e.ActionId == "Action1") // 查看详情
                    {
                        ShowMainWindow();
                        notificationForm.CloseNotification();
                    }
                    else if (e.ActionId == "Action2") // 忽略
                    {
                        notificationForm.CloseNotification();
                    }
                };
                
                notificationForm.NotificationClicked += (sender, e) =>
                {
                    ShowMainWindow();
                };
                
                // 显示通知
                notificationForm.ShowNotification();
            }
            catch
            {
                Console.WriteLine("显示消息通知时发生错误");
            }
        }
        
        /// <summary>
        /// 显示主窗口
        /// </summary>
        private void ShowMainWindow()
        {
            try
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.WindowState = FormWindowState.Normal;
                }
                
                this.Show();
                this.Activate();
                this.BringToFront();
            }
            catch
            {
                Console.WriteLine("显示主窗口时发生错误");
            }
        }
        
        /// <summary>
        /// 托盘图标双击事件
        /// </summary>
        private void NotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            ShowMainWindow();
        }
        
        /// <summary>
        /// 托盘气泡提示点击事件
        /// </summary>
        private void NotifyIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            ShowMainWindow();
        }
        
        /// <summary>
        /// 显示主窗口菜单项点击事件
        /// </summary>
        private void ShowMainWindow_Click(object sender, EventArgs e)
        {
            ShowMainWindow();
        }
        
        /// <summary>
        /// 退出程序菜单项点击事件
        /// </summary>
        private void ExitApplication_Click(object sender, EventArgs e)
        {
            try
            {
                // 清理资源
                if (notifyIcon != null)
                {
                    notifyIcon.Visible = false;
                    notifyIcon.Dispose();
                }
                
                if (trayContextMenu != null)
                {
                    trayContextMenu.Dispose();
                }
                
                // 断开消息推送连接 - 已注释
                /*
                if (messagePushClient != null)
                {
                    messagePushClient.Disconnect();
                }
                */
                
                // 关闭整个应用程序，包括登录窗体
                Application.Exit();
            }
            catch
            {
                Console.WriteLine("退出程序时发生错误");
                Application.Exit();
            }
        }
        
        // 标志位，防止重复弹出关闭确认对话框
        private bool isClosingConfirmed = false;

        /// <summary>
        /// 窗体关闭事件重写
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 如果已经确认关闭，直接执行清理并关闭
            if (isClosingConfirmed)
            {
                // 执行清理操作
                if (notifyIcon != null)
                {
                    notifyIcon.Visible = false;
                    notifyIcon.Dispose();
                }
                
                if (trayContextMenu != null)
                {
                    trayContextMenu.Dispose();
                }
                
                base.OnFormClosing(e);
                return;
            }

            // 如果是用户点击关闭按钮，则提示用户选择是关闭程序还是最小化到托盘
            if (e.CloseReason == CloseReason.UserClosing)
            {
                // 显示对话框，让用户选择是关闭程序还是最小化到托盘
                DialogResult result = MessageBox.Show(
                    "您确定要关闭程序吗？\n\n点击\"是\"关闭整个程序\n点击\"否\"最小化到系统托盘",
                    "关闭程序",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    // 用户选择关闭程序，设置标志位并重新触发关闭
                    isClosingConfirmed = true;
                    this.Close();
                }
                else
                {
                    // 用户选择最小化到托盘
                    e.Cancel = true;
                    this.Hide();
                    
                    // 显示托盘提示
                    if (notifyIcon != null)
                    {
                        notifyIcon.ShowBalloonTip(2000, "程序已最小化", "程序已最小化到系统托盘，双击托盘图标可重新打开", ToolTipIcon.Info);
                    }
                }
            }
            else
            {
                // 其他原因导致的关闭，直接执行清理操作
                if (notifyIcon != null)
                {
                    notifyIcon.Visible = false;
                    notifyIcon.Dispose();
                }
                
                if (trayContextMenu != null)
                {
                    trayContextMenu.Dispose();
                }
                
                base.OnFormClosing(e);
            }
        }

        /// <summary>
        /// 患者数据查询测试按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestPatientQuery_Click(object sender, EventArgs e)
        {
            try
            {
                // 同步功能
                string syncResult = TestSync.ExecuteSyncTest();
                MessageBox.Show(syncResult, "环境同步测试结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
                
                // 原有的患者查询代码（暂时注释）
                /*
                // 创建输入对话框获取用户ID
                string userId = Microsoft.VisualBasic.Interaction.InputBox(
                    "请输入用户ID（例如：12880）:",
                    "患者数据查询测试",
                    "12880");

                if (string.IsNullOrWhiteSpace(userId))
                {
                    MessageBox.Show("用户ID不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 显示等待提示
                this.Cursor = Cursors.WaitCursor;
                this.Enabled = false;

                // 异步调用患者数据查询接口
                ThreadPool.QueueUserWorkItem(delegate
                {
                    try
                    {
                        var response = PatientDataService.QueryPatientData(userId);

                        // 回到UI线程显示结果
                        this.Invoke(new MethodInvoker(delegate
                        {
                            try
                            {
                                this.Cursor = Cursors.Default;
                                this.Enabled = true;

                                // 创建并显示结果窗体
                                using (var resultForm = new PatientDataResultForm())
                                {
                                    resultForm.ShowPatientData(response);
                                    resultForm.ShowDialog(this);
                                }
                            }
                            catch
                            {
                                MessageBox.Show("显示结果时发生错误", "错误", 
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }));
                    }
                    catch
                    {
                        // 回到UI线程显示错误
                        this.Invoke(new MethodInvoker(delegate
                        {
                            this.Cursor = Cursors.Default;
                            this.Enabled = true;
                            MessageBox.Show("查询患者数据时发生错误", "错误", 
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }));
                    }
                });
                */
            }
            catch
            {
                MessageBox.Show("测试同步功能时发生错误", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion
        
        #region 公共方法 - 供MessageNotificationForm调用
        /// <summary>
        /// 设置控件状态
        /// </summary>
        /// <param name="lis_count"></param>
        /// <param name="exam_count"></param>
        public void SetBtLisExamStatus(string lis_count,string exam_count,string _id)
        {
            tb_reporturl.Text = string.Empty;
            if (lis_count != "0" || exam_count !="0")
            {
                string _url = ConfigurationManager.AppSettings["hisUrl"].ToString() + "His/getQueryUrl?query_id=" + _id;
                string reportUrl = CodeHelper.HttpGetJson(_url);
                tb_reporturl.Text = reportUrl;
                if (lis_count != "0")
                {
                    bt_lis.Visible = true;
                }
                else
                {
                    bt_lis.Visible = false;
                }
                if (exam_count != "0")
                {
                    bt_exam.Visible = true;
                }
                else
                {
                    bt_exam.Visible = false;
                }
            }
            else
            {
                bt_lis.Visible = false;
                bt_exam.Visible = false;
                reportUrl = string.Empty;
                tb_reporturl.Text = reportUrl;
            }
            
        }
        
        /// <summary>
        /// 设置textBoxcx的值
        /// </summary>
        /// <param name="value">要设置的值</param>
        public void SetTextBoxcxValue(string value)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(SetTextBoxcxValue), value);
            }
            else
            {
                this.textBoxcx.Text = value;
            }
        }
        
        /// <summary>
        /// 触发button2的Click事件
        /// </summary>
        public void TriggerButton2Click()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(TriggerButton2Click));
            }
            else
            {
                this.button2_Click(this.button2, EventArgs.Empty);
            }
        }
        #endregion
        
        #region 医生患者记录数据加载
        /// <summary>
        /// 加载医生患者记录数据
        /// </summary>
        private void LoadDoctorPatientRecords()
        {
            try
            {
                Console.WriteLine("开始加载医生患者记录数据...");
                
                if (userData == null)
                {
                    Console.WriteLine("userData为null，可能是因为没有通过登录流程启动程序");
                    return;
                }
                
                if (string.IsNullOrWhiteSpace(userData.user_id))
                {
                    Console.WriteLine("用户ID为空，无法获取医生患者记录");
                    return;
                }
                
                Console.WriteLine($"当前用户ID: {userData.user_id}");
                
                // 调用GetDoctorPatientRecords接口
                var response = PatientDataService.GetDoctorPatientRecords(userData.user_id);
                
                if (response != null && response.Success && response.Data != null && response.Data.Length > 0)
                {
                    Console.WriteLine($"获取到 {response.Data.Length} 条医生患者记录数据");
                    
                    // 将数据导入LocalData.xml
                    foreach (var patientData in response.Data)
                    {
                        try
                        {
                            // 构造与定时查询相同格式的JSON数据
                            var apiFormatData = new
                            {
                                success = true,
                                message = "数据获取成功",
                                data = new
                                {
                                    outP_VISIT_ID = patientData.OutpVisitId,
                                    patienT_ID = patientData.PatientId,
                                    patI_NAME = patientData.PatientName,
                                    outP_SPECIAL_NAME = patientData.OutpSpecialName,
                                    outP_DATE = patientData.OutpDate,
                                    visiT_ID = patientData.VisitId,
                                    admissioN_DOCTOR = patientData.AdmissionDoctor,
                                    doctoR_VS_OUTP_VISIT_ID = patientData.DoctorVsOutpVisitId,
                                    qR_CODE = patientData.QrCode,
                                    registratioN_FEE_STATUS = patientData.RegistrationFeeStatus,
                                    paT_LEVEL = patientData.PatLevel,
                                    liS_COUNT = patientData.LisCount,
                                    exaM_COUNT = patientData.ExamCount,
                                    reaD_FLAG = patientData.ReadFlag,
                                    ordeR_NAMES = patientData.OrderNames
                                }
                            };
                            
                            // 序列化为JSON字符串
                            string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(apiFormatData);
                            
                            // 保存到本地数据库
                            TimerTaskDataProcessor.ProcessPatientData(jsonData);
                        }
                        catch
                        {
                            Console.WriteLine($"处理患者数据失败，outP_VISIT_ID: {patientData.OutpVisitId}");
                        }
                    }
                    
                    // 刷新本地数据显示
                    LoadLocalData();
                    
                    Console.WriteLine("医生患者记录数据导入完成");
                }
                else
                {
                    string errorMsg = response?.Message ?? "未知错误";
                    Console.WriteLine($"获取医生患者记录失败: {errorMsg}");
                }
            }
            catch
            {
                Console.WriteLine("加载医生患者记录数据异常");
            }
        }
        #endregion
        
        #region 本地数据处理
        /// <summary>
        /// 加载本地数据到DataGridView
        /// </summary>
        private void LoadLocalData()
        {
            try
            {
                dgvLocalData.Rows.Clear();
                
                // 订阅 CellFormatting 事件
                dgvLocalData.CellFormatting -= dgvLocalData_CellFormatting; // 先取消订阅避免重复
                dgvLocalData.CellFormatting += dgvLocalData_CellFormatting;
                
                // 订阅 CellContentClick 事件，用于处理按钮点击
                dgvLocalData.CellContentClick -= dgvLocalData_CellContentClick; // 先取消订阅避免重复
                dgvLocalData.CellContentClick += dgvLocalData_CellContentClick;
                
                // 从LocalDbHelper获取数据
                var localData = LocalDbHelper.GetTodayPatientVisitData();
                
                if (localData != null && localData.Count > 0)
                {
                    // 按outP_VISIT_ID降序排序（最大的在上面）
                    var sortedData = localData.OrderByDescending(x => 
                    {
                        if (x.ContainsKey("outP_VISIT_ID") && long.TryParse(x["outP_VISIT_ID"], out long id))
                            return id;
                        return 0;
                    }).ToList();
                    
                    foreach (var item in sortedData)
                    {
                        int rowIndex = dgvLocalData.Rows.Add();
                        dgvLocalData.Rows[rowIndex].Cells["colViewButton"].Value = "查阅";
                        dgvLocalData.Rows[rowIndex].Cells["colPatientName"].Value = item.ContainsKey("patI_NAME") ? item["patI_NAME"] : "";
                        dgvLocalData.Rows[rowIndex].Cells["colOrderNames"].Value = item.ContainsKey("ordeR_NAMES") ? item["ordeR_NAMES"] : "";
                        dgvLocalData.Rows[rowIndex].Cells["colOutpVisitId"].Value = item.ContainsKey("patienT_ID") ? item["patienT_ID"] : "";
                        dgvLocalData.Rows[rowIndex].Cells["colPatLevel"].Value = item.ContainsKey("paT_LEVEL") ? item["paT_LEVEL"] : "";
                        dgvLocalData.Rows[rowIndex].Cells["colSpecialName"].Value = item.ContainsKey("outP_SPECIAL_NAME") ? item["outP_SPECIAL_NAME"] : "";
                        dgvLocalData.Rows[rowIndex].Cells["outp_visit_id"].Value = item.ContainsKey("outP_VISIT_ID") ? item["outP_VISIT_ID"] : "";

                        // 设置互认检验按钮
                        string lisCount = item.ContainsKey("liS_COUNT") ? item["liS_COUNT"] : "0";
                        dgvLocalData.Rows[rowIndex].Cells["colLisCount"].Value = lisCount;
                        if (lisCount != "0")
                        {
                            dgvLocalData.Rows[rowIndex].Cells["colLisCount"].Style.BackColor = Color.MediumSpringGreen;
                        }
                        
                        // 设置互认检查按钮
                        string examCount = item.ContainsKey("exaM_COUNT") ? item["exaM_COUNT"] : "0";
                        dgvLocalData.Rows[rowIndex].Cells["colExamCount"].Value = examCount;
                        if (examCount != "0")
                        {
                            dgvLocalData.Rows[rowIndex].Cells["colExamCount"].Style.BackColor = Color.PeachPuff;
                        }
                        
                        dgvLocalData.Rows[rowIndex].Cells["colRegistrationFeeStatus"].Value = item.ContainsKey("registratioN_FEE_STATUS") ? item["registratioN_FEE_STATUS"] : "";
                        
                        // 存储完整的数据对象到Tag中，方便后续使用
                        dgvLocalData.Rows[rowIndex].Tag = item;
                    }
                }
            }
            catch
            {
                MessageBox.Show("加载本地数据失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// dgvLocalData的CellFormatting事件处理方法
        /// </summary>
        private void dgvLocalData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridView dataGridView = (DataGridView)sender;
                DataGridViewRow row = dataGridView.Rows[e.RowIndex];

                // 找到 colOrderNames 列的索引
                if (dataGridView.Columns.Contains("colOrderNames"))
                {
                    int orderNamesColumnIndex = dataGridView.Columns["colOrderNames"].Index;
                    DataGridViewCell orderNamesCell = row.Cells[orderNamesColumnIndex];

                    if (orderNamesCell.Value != null)
                    {
                        string cellValue = orderNamesCell.Value.ToString();
                        if (cellValue.Contains("已计费"))
                        {
                            // 使用浅绿颜色
                            row.DefaultCellStyle.BackColor = Color.LightGreen;
                        }
                        else if (cellValue.Contains("未计费"))
                        {
                            row.DefaultCellStyle.BackColor = Color.Red;
                        }
                        else if (cellValue.Contains("未开诊查费"))
                        {
                            row.DefaultCellStyle.BackColor = Color.Yellow;
                        }
                        else
                        {
                            // 恢复默认颜色
                            row.DefaultCellStyle.BackColor = SystemColors.Window;
                        }
                        
                        // 确保按钮列不受行颜色影响
                        if (dataGridView.Columns.Contains("colLisCount"))
                        {
                            int lisCountIndex = dataGridView.Columns["colLisCount"].Index;
                            if (row.Cells[lisCountIndex].Value != null && row.Cells[lisCountIndex].Value.ToString() != "0")
                            {
                                row.Cells[lisCountIndex].Style.BackColor = Color.MediumSpringGreen;
                            }
                        }
                        
                        if (dataGridView.Columns.Contains("colExamCount"))
                        {
                            int examCountIndex = dataGridView.Columns["colExamCount"].Index;
                            if (row.Cells[examCountIndex].Value != null && row.Cells[examCountIndex].Value.ToString() != "0")
                            {
                                row.Cells[examCountIndex].Style.BackColor = Color.PeachPuff;
                            }
                        }
                    }
                }
            }
        }
        
        /// <summary>
        /// dgvLocalData的CellContentClick事件处理方法
        /// </summary>
        private void dgvLocalData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dataGridView = (DataGridView)sender;
            if (e.RowIndex >= 0 && (dataGridView.Columns[e.ColumnIndex].Name == "colLisCount" || dataGridView.Columns[e.ColumnIndex].Name == "colExamCount"))
            {
                DataGridViewCell cell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                if (cell.Value != null)
                {
                    string value = cell.Value.ToString();
                    if (value != "0")
                    {
                        // 获取选中行的数据
                        var selectedData = dgvLocalData.Rows[e.RowIndex].Tag as Dictionary<string, string>;
                        if (selectedData != null && selectedData.ContainsKey("doctoR_VS_OUTP_VISIT_ID"))
                        {
                            string idValue = selectedData["doctoR_VS_OUTP_VISIT_ID"].Split('&')[4];
                            // 在这里可以使用获取到的 id 值进行后续处理
                            string _url = ConfigurationManager.AppSettings["hisUrl"].ToString() + "His/getQueryUrl?query_id=" + idValue;
                            string _viewUrl = CodeHelper.HttpGetJson(_url);
                            //MessageBox.Show(_viewUrl);
                            string[] browserPaths = {
                                @"C:\Program Files\Google\Chrome\Application\chrome.exe",
                                @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
                                @"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
                                @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
                            };

                            string browserPath = null;
                            foreach (string path in browserPaths)
                            {
                                if (System.IO.File.Exists(path))
                                {
                                    browserPath = path;
                                    break;
                                }
                            }

                            if (browserPath != null)
                            {
                                System.Diagnostics.Process.Start(browserPath, _viewUrl);
                            }
                            else
                            {
                                // 如果没有找到浏览器，使用默认方式打开
                                System.Diagnostics.Process.Start(_viewUrl);
                            }
                        }
                    }
                }
            }
        }
        
        /// <summary>
        /// 处理DataGridView单元格点击事件
        /// </summary>
        private void dgvLocalData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                // 检查是否点击了查阅按钮列
                if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && 
                    dgvLocalData.Columns[e.ColumnIndex].Name == "colViewButton")
                {
                    // 获取选中行的数据
                    var selectedData = dgvLocalData.Rows[e.RowIndex].Tag as Dictionary<string, string>;
                    if (selectedData != null)
                    {
                        // 显示详细信息
                        //ShowPatientDetails(selectedData);
                        // 设置QR_CODE到textBoxcx
                        Clipboard.SetText(selectedData["qR_CODE"]);
                        SetTextBoxcxValue(selectedData["qR_CODE"]);

                        // 触发button2的Click事件
                        TriggerButton2Click();

                        SetBtLisExamStatus(selectedData["liS_COUNT"], selectedData["exaM_COUNT"], selectedData["doctoR_VS_OUTP_VISIT_ID"].Split('&')[4]);
                    }
                    /*
                     * $"就诊ID：{(patientInfo.ContainsKey("outP_VISIT_ID") ? patientInfo["outP_VISIT_ID"] : "")}\n" +
                               $"患者ID：{(patientInfo.ContainsKey("patienT_ID") ? patientInfo["patienT_ID"] : "")}\n" +
                               $"患者姓名：{(patientInfo.ContainsKey("patI_NAME") ? patientInfo["patI_NAME"] : "")}\n" +
                               $"就诊日期：{(patientInfo.ContainsKey("outP_DATE") ? patientInfo["outP_DATE"] : "")}\n" +
                               $"科室：{(patientInfo.ContainsKey("outP_SPECIAL_NAME") ? patientInfo["outP_SPECIAL_NAME"] : "")}\n" +
                               $"就诊ID：{(patientInfo.ContainsKey("visiT_ID") ? patientInfo["visiT_ID"] : "")}\n" +
                               $"接诊医生：{(patientInfo.ContainsKey("admissioN_DOCTOR") ? patientInfo["admissioN_DOCTOR"] : "")}\n" +
                               $"二维码：{(patientInfo.ContainsKey("qR_CODE") ? patientInfo["qR_CODE"] : "")}\n" +
                               $"挂号费状态：{(patientInfo.ContainsKey("registratioN_FEE_STATUS") ? patientInfo["registratioN_FEE_STATUS"] : "")}\n" +
                               $"患者级别：{(patientInfo.ContainsKey("paT_LEVEL") ? patientInfo["paT_LEVEL"] : "")}\n" +
                               $"检验数量：{(patientInfo.ContainsKey("liS_COUNT") ? patientInfo["liS_COUNT"] : "")}\n" +
                               $"检查数量：{(patientInfo.ContainsKey("exaM_COUNT") ? patientInfo["exaM_COUNT"] : "")}\n" +
                               $"已读标志：{(patientInfo.ContainsKey("reaD_FLAG") ? patientInfo["reaD_FLAG"] : "")}\n" +
                               $"创建时间：{(patientInfo.ContainsKey("CreateTime") ? patientInfo["CreateTime"] : "")}";
                     */
                    // 设置QR_CODE到textBoxcx
                    //SetTextBoxcxValue(selectedData.QrCode);

                    // 触发button2的Click事件
                    //TriggerButton2Click();

                    //SetBtLisExamStatus(selectedData.LisCount, selectedData.ExamCount, selectedData.DoctorVsOutpVisitId.Split('&')[4]);
                }
            }
            catch
            {
                MessageBox.Show("处理查阅操作失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 显示患者详细信息
        /// </summary>
        private void ShowPatientDetails(Dictionary<string, string> patientInfo)
        {
            try
            {
                string details = $"患者详细信息：\n\n" +
                               $"就诊ID：{(patientInfo.ContainsKey("outP_VISIT_ID") ? patientInfo["outP_VISIT_ID"] : "")}\n" +
                               $"患者ID：{(patientInfo.ContainsKey("patienT_ID") ? patientInfo["patienT_ID"] : "")}\n" +
                               $"患者姓名：{(patientInfo.ContainsKey("patI_NAME") ? patientInfo["patI_NAME"] : "")}\n" +
                               $"就诊日期：{(patientInfo.ContainsKey("outP_DATE") ? patientInfo["outP_DATE"] : "")}\n" +
                               $"科室：{(patientInfo.ContainsKey("outP_SPECIAL_NAME") ? patientInfo["outP_SPECIAL_NAME"] : "")}\n" +
                               $"就诊ID：{(patientInfo.ContainsKey("visiT_ID") ? patientInfo["visiT_ID"] : "")}\n" +
                               $"接诊医生：{(patientInfo.ContainsKey("admissioN_DOCTOR") ? patientInfo["admissioN_DOCTOR"] : "")}\n" +
                               $"二维码：{(patientInfo.ContainsKey("qR_CODE") ? patientInfo["qR_CODE"] : "")}\n" +
                               $"挂号费状态：{(patientInfo.ContainsKey("registratioN_FEE_STATUS") ? patientInfo["registratioN_FEE_STATUS"] : "")}\n" +
                               $"患者级别：{(patientInfo.ContainsKey("paT_LEVEL") ? patientInfo["paT_LEVEL"] : "")}\n" +
                               $"检验数量：{(patientInfo.ContainsKey("liS_COUNT") ? patientInfo["liS_COUNT"] : "")}\n" +
                               $"检查数量：{(patientInfo.ContainsKey("exaM_COUNT") ? patientInfo["exaM_COUNT"] : "")}\n" +
                               $"已读标志：{(patientInfo.ContainsKey("reaD_FLAG") ? patientInfo["reaD_FLAG"] : "")}\n" +
                               $"创建时间：{(patientInfo.ContainsKey("CreateTime") ? patientInfo["CreateTime"] : "")}";
                
                MessageBox.Show(details, "患者信息查阅", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("显示患者详细信息失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 显示本机IP地址
        /// </summary>
        public void DisplayIPAddress()
        {
            try
            {
                string hostName = Dns.GetHostName();
                IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
                string ipAddress = "";

                foreach (IPAddress ip in hostEntry.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ipAddress = ip.ToString();
                        break;
                    }
                }

                // 更新LB_IP控件的Text属性
                if (LB_IP != null)
                {
                    this.Invoke(new MethodInvoker(() =>
                    {
                        LB_IP.Text = "本机IP:" + ipAddress;
                    }));
                }
            }
            catch (SocketException)
            {
                MessageBox.Show("发生套接字错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception)
            {
                MessageBox.Show("发生未知错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion
        
        #region 显示本机MAC地址二维码
        /// <summary>
        /// 显示本机MAC地址二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_display_qrcode_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取本机MAC地址
                string macAddress = GetLocalMacAddress();
                
                if (!string.IsNullOrEmpty(macAddress) && macAddress != "获取失败")
                {
                    // 生成二维码
                    Bitmap qrCodeBitmap = QrCodeHelper.CreateQRCode(macAddress);
                    
                    // 创建新窗口显示二维码
                    Form qrForm = new Form()
                    {
                        Text = "本机MAC地址二维码",
                        Size = new Size(400, 450),
                        StartPosition = FormStartPosition.CenterParent,
                        FormBorderStyle = FormBorderStyle.FixedDialog,
                        MaximizeBox = false,
                        MinimizeBox = false
                    };
                    
                    // 创建PictureBox显示二维码
                    PictureBox picQrCode = new PictureBox()
                    {
                        Image = qrCodeBitmap,
                        SizeMode = PictureBoxSizeMode.CenterImage,
                        Size = new Size(300, 300),
                        Location = new Point(50, 20)
                    };
                    
                    // 创建标签显示MAC地址文本
                    Label lblMacAddress = new Label()
                    {
                        Text = "MAC地址: " + macAddress,
                        Font = new Font("宋体", 12, FontStyle.Bold),
                        AutoSize = true,
                        Location = new Point(50, 330),
                        ForeColor = Color.Blue
                    };
                    
                    // 创建关闭按钮
                    Button btnClose = new Button()
                    {
                        Text = "关闭",
                        Size = new Size(80, 30),
                        Location = new Point(160, 360),
                        DialogResult = DialogResult.OK
                    };
                    
                    // 添加控件到窗口
                    qrForm.Controls.Add(picQrCode);
                    qrForm.Controls.Add(lblMacAddress);
                    qrForm.Controls.Add(btnClose);
                    
                    // 显示窗口
                    qrForm.ShowDialog(this);
                }
                else
                {
                    MessageBox.Show("无法获取本机MAC地址！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成MAC地址二维码失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 获取本机MAC地址
        /// </summary>
        /// <returns>MAC地址字符串，格式如"8C:32:23:3A:AC:71"</returns>
        private string GetLocalMacAddress()
        {
            try
            {
                foreach (var nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && 
                        nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback &&
                        nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Tunnel)
                    {
                        var macBytes = nic.GetPhysicalAddress().GetAddressBytes();
                        if (macBytes.Length > 0)
                        {
                            return string.Join(":", macBytes.Select(b => b.ToString("X2")));
                        }
                    }
                }
                return "获取失败";
            }
            catch
            {
                return "获取失败";
            }
        }
        #endregion

        private void bt_reflash_patlist_Click(object sender, EventArgs e)
        {
            try
            {
                // 在后台线程执行数据刷新任务，避免阻塞UI
                ThreadPool.QueueUserWorkItem(state =>
                {
                    try
                    {
                        // 清空本地数据库
                        bool clearResult = LocalDbHelper.ClearAllData();

                        // 在UI线程更新界面
                        if (this != null)
                        {
                            this.Invoke(new MethodInvoker(() =>
                            {
                                // 刷新数据窗口显示清空后的状态
                                LoadLocalData();

                                // 重新获取医生接诊数据
                                LoadDoctorPatientRecords();
                            }));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"数据刷新定时器事件处理时发生错误: {ex.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据刷新定时器事件处理时发生错误: {ex.Message}");
            }
        }
    }

}
